How do I programmatically “restart” an Android app?

后端 未结 26 2453
小鲜肉
小鲜肉 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:29

    Ok, I refactored my app and I will not finish A automatically. I let this run always and finish it through the onActivityResult event. In this way I can use the FLAG_ACTIVITY_CLEAR_TOP + FLAG_ACTIVITY_NEW_TASK flags to get what I want:

    public class A extends Activity {
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            finish();
        }
    
        protected void onResume() {
            super.onResume();
            // ...
            if (loggedIn) {
                startActivityForResult(new Intent(this, MainActivity.class), 0);
            } else {
                startActivityForResult(new Intent(this, LoginActivity.class), 0);
            }
        }
    }
    

    and in the ResultReceiver

    @Override
    public void onClick(DialogInterface dialog, int which) {
        MyApp.factoryReset();
        Intent i = new Intent(MyApp.getContext(), A.class);
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        MyApp.getContext().startActivity(i);
    }
    

    Thanks anyway!

提交回复
热议问题