Search code examples
androidandroid-activityrecreate

Android - prevent recreating activity when returning from web browser


In my activity B I have option "Help" which opens URL in web browser. When returning from web browser (with back key) activity is recreated. Why is this happening and how to prevent this?

EDIT: This is how i call web browser:

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.help_url)));
startActivity(browserIntent);

When returning from browser onCreate() is called;

My logical operations: When starting app, activity A reads settings and write it to activity/class C. After that I start activty B and finish() activity A. In activity B, onCreate() method is reading some settings from activity C.


Solution

  • To do that you must finish your Activity before starting browser.

    Change your code to:

    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.help_url)));
    finish(); // should be called from your current activity
    startActivity(browserIntent);
    

    Android doesn't store all information from your current Activity when it goes to other (i.e. to WebBrowser), so activity must be recreated to show it again.

    If you still need this Activity after coming back from WebBrowser there is no way to prevent Android from recreating it. You should save all you need overriding onSaveInstanceState and recreate your Activity using savedInstanceState.

    Look at Activity lifecycle. When Android need to free some memory for others processes it may kill your app (which is in background). There are also other possible paths back to your Activity running state which doesn't recreate it. (onPause -> onResume and onStop -> onRestart -> onStart -> onResume)