I am writing a custom React Native module in Java for Android so I can programmatically move the app into the background using the back button.
I am using the backHandler built in to React Native, but it only supplies a method to exit the app completely, not move the app to the background.
When implemented, in my JavaScript code, I will call my native module here:
BackHandler.addEventListener('hardwareBackPress', function () {
/**
* call native module here
*/
return true;
}
The recommended way of moving the app to the back using the back navigation button on Android is by adding a method to the MainActivity as described here. But this will cause the app to always to go the background on every back button press. As I want to move the app to the background programmatically, I want to make my own module that I can call at any time.
The difficulty I am facing is how to move this method from MainActivity to a custom module.
The code I have so far is:
Package:
package com.myApp;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import java.util.ArrayList;
import java.util.List;
public class MoveAppToBackgroundPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new MoveAppToBackground(reactContext));
return modules;
}
}
Module:
package com.myApp;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReactContext;
public class MoveAppToBackground extends ReactContextBaseJavaModule {
@Override
public String getName() {
return "MoveAppToBackground";
}
private ReactContext mReactContext;
public MoveAppToBackground(ReactApplicationContext reactContext) {
super(reactContext);
mReactContext = reactContext;
}
/* React Methods */
@ReactMethod
public void MoveToBackground() {
Activity activity = mReactContext.getCurrentActivity();
activity.moveTaskToBack(true);
}
}
MainApplication:
...
packages.add(new MoveAppToBackgroundPackage());
...
The error I'm getting when I compile the app is:
MoveAppToBackgroundPackage is not abstract and does not override abstract method createViewManagers(ReactApplicationContext
How can I create this method that I can call in a custom module that moves the app to the background?