How to restart an application completely?

WhiskThimble picture WhiskThimble · Jun 25, 2013 · Viewed 13.9k times · Source

I have an application which starts a Remote Service in its first launched activity. Then, in another activity, the user can set the configuration of the application. Please note that this second activity isn't bound to the Service and I don't wish to bind it.

Now my question is : how could I restart the whole application from the second activity, after changing the configuration settings?

For now, I am using a button which onClickListener is :

public void onClick(DialogInterface dialog, int which) {
    sauvegarde();
    Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i);
}

The problem is : it only restarts the current activity without shutting the whole application, and therefore, without restarting the service

Any ideas?

Answer

alex picture alex · Jun 25, 2013

You can use the Androids system AlarmManager like this:

Code to restart the app in your activity:

AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, PendingIntent.getActivity(this.getBaseContext(), 0, new    Intent(getIntent()), getIntent().getFlags()));
System.exit(2);

An example can be looked up here

UPDATE

As @CommonsWare pointed out, its a bad way to design your app, when you have to restart it (bad practice). If you really want to do it, you can try setting alarmmanager to start your app in a second after you killed your own process:

AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, PendingIntent.getActivity(this.getBaseContext(), 0, new    Intent(getIntent()), getIntent().getFlags()));
android.os.Process.killProcess(android.os.Process.myPid());