I am using this code to go back to the previous activity in Android:
@ReactMethod
public void goBack()
{
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
MainApplication.getContext().startActivity(startMain);
}
The problem is when I open a link (deep link) from Gmail for example, my app opens on top of the Gmail app and when I'm pressing the back button it shows me the following message:
What I want is to go back to the previous app or to the Home screen without finishing or killing my app.
I want it to be as if I pressed the multi-apps button and chosen the previous app without closing my app. When I'm using the back button as it is it finishes my app. I tried playing with the flags but without success.
There is a Cordova solution for this : https://github.com/mohamed-salah/phonegap-backbutton-plugin/blob/master/src/android/BackbuttonPlugin.java. Mine is a React Native project.
Any help will be much appreciated!
After some digging I used a different code:
@ReactMethod
public void goBack()
{
MainApplication.getCurrentActivity().moveTaskToBack (true);
}
In MainApplication.java:
public class MainApplication extends Application implements ReactApplication
{
private static Activity currentActivity;
@Override
public void onCreate() {
super.onCreate();
// Used for BackButton Module
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
MainApplication.currentActivity = activity;
}
@Override
public void onActivityStarted(Activity activity) {
MainApplication.currentActivity = activity;
}
@Override
public void onActivityResumed(Activity activity) {
MainApplication.currentActivity = activity;
}
@Override
public void onActivityPaused(Activity activity) {
MainApplication.currentActivity = null;
}
@Override
public void onActivityStopped(Activity activity) {
// don't clear current activity because activity may get stopped after
// the new activity is resumed
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
// don't clear current activity because activity may get destroyed after
// the new activity is resumed
}
});
}
public static Activity getCurrentActivity()
{
return currentActivity;
}
}