简体   繁体   中英

How to always start top activity when app is restarted by Android

In my application I have 2 activities, A and B. Activity A performs some global initialization, displays splash, connects to the back end to fetch some user info, etc... and then launches activity B. While in activity B, if the user decides to revoke some permissions from the App, the Android kills the entire process and restarts the App (Marshmallow behavior), but it launches activity B, which makes sense from the user perspective - it takes you back to where you left off. But the initialization that was done in activity A is thus never performed. How can I force activity A (which is by the way marked as the LAUNCHER activity in the Manifest) to be always launched upon restarts?

I can detect this condition in activity B and perform the required initialization there, but in the real App there are many activities and I would like to not have to perform initialization in all children activities when this condition occurs.

You can perform global initialization in your custom Application, and configure the manifest file to use your application.

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        // Called when the application is starting, before any activity, service
        init();
    }

    private void init() {
        android.util.Log.i("MyApplication", "initialize");
    }
}

And in AndroidManifest.xml file:

<application
    android:name=".MyApplication"
    ...>

Or use a base activity, make other activities who need to perform initialization extend the base activity.

public class BaseActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!isInitialized()) {
            startActivity(new Intent(this, SplashActivity.class));
            finish();
        }
    }

    private boolean isInitialized() {
        // your initialization state
        return false;
    }
}

there is a work around, you can start the activity A in the onDestroy method of the activity B. If you set an appropriate flag to then Intent , you can get the result as the description.

some codes below:

// Activity B
@Override
protected void onDestroy() {
    super.onDestroy();
    Intent intent = new Intent(this, A.class);
    // this flag will clear all activity and retain activity A
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);
}

in my test, this work.

in your case, you should check the destroy timing if onDestroy called because user decides to revoke some permissions from the App,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM