How do I programmatically “restart” an Android app?

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

    Kotlin version of this answer:

    val intent = Intent(this, YourActivity::class.java)
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
    startActivity(intent)
    Runtime.getRuntime().exit(0)
    
    0 讨论(0)
  • 2020-11-22 13:19

    You can use PendingIntent to setup launching your start activity in the future and then close your application

    Intent mStartActivity = new Intent(context, StartActivity.class);
    int mPendingIntentId = 123456;
    PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
    System.exit(0);
    
    0 讨论(0)
  • 2020-11-22 13:20

    My solution doesn't restart the process/application. It only lets the app "restart" the home activity (and dismiss all other activities). It looks like a restart to users, but the process is the same. I think in some cases people want to achieve this effect, so I just leave it here FYI.

    public void restart(){
        Intent intent = new Intent(this, YourHomeActivity.class);
        this.startActivity(intent);
        this.finishAffinity();
    }
    
    0 讨论(0)
  • 2020-11-22 13:21

    try this:

    private void restartApp() {
        Intent intent = new Intent(getApplicationContext(), YourStarterActivity.class);
        int mPendingIntentId = MAGICAL_NUMBER;
        PendingIntent mPendingIntent = PendingIntent.getActivity(getApplicationContext(), mPendingIntentId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager mgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
        System.exit(0);
    }
    
    0 讨论(0)
  • 2020-11-22 13:25

    in MainActivity call restartActivity Method:

    public static void restartActivity(Activity mActivity) {
        Intent mIntent = mActivity.getIntent();
        mActivity.finish();
        mActivity.startActivity(mIntent);
    }
    
    0 讨论(0)
  • 2020-11-22 13:28

    Jake Wharton recently published his ProcessPhoenix library, which does this in a reliable way. You basically only have to call:

    ProcessPhoenix.triggerRebirth(context);
    

    The library will automatically finish the calling activity, kill the application process and restart the default application activity afterwards.

    0 讨论(0)
提交回复
热议问题