How do I programmatically “restart” an Android app?

后端 未结 26 2305
小鲜肉
小鲜肉 2020-11-22 12:42

Firstly, I know that one should not really kill/restart an application on Android. In my use case, I want to factory-reset my application in a specific case where a server s

26条回答
  •  心在旅途
    2020-11-22 13:05

    My best way to restart application is to use finishAffinity();
    Since, finishAffinity(); can be used on JELLY BEAN versions only, so we can use ActivityCompat.finishAffinity(YourCurrentActivity.this); for lower versions.

    Then use Intent to launch first activity, so the code will look like this:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        finishAffinity();
        Intent intent = new Intent(getApplicationContext(), YourFirstActivity.class);
        startActivity(intent);
    } else {
        ActivityCompat.finishAffinity(YourCurrentActivity.this);
        Intent intent = new Intent(getApplicationContext(), YourFirstActivity.class);
        startActivity(intent);
    }
    

    Hope it helps.

提交回复
热议问题