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
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)
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);
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();
}
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);
}
in MainActivity call restartActivity Method:
public static void restartActivity(Activity mActivity) {
Intent mIntent = mActivity.getIntent();
mActivity.finish();
mActivity.startActivity(mIntent);
}
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.