10

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?

WhiskThimble
  • 487
  • 3
  • 10
  • 22
  • try `System.exit(0)`. – dd619 Jun 25 '13 at 10:13
  • 1
    @dd619, I disagree with use of `System.exit(0)` in android.. [refer here](http://stackoverflow.com/a/16480930/2345913) – CRUSADER Jun 25 '13 at 10:19
  • 2
    Talented programmers would not "restart the whole application", to the extent such a thing is even possible. Talented programmers would use the observer pattern to allow application components that depend upon this "configuration" to know about changes. An example would be using `SharedPreferences` to store the "configuration", with other components registering `OnSharedPreferenceChangedListener` instances to find out about relevant changes. – CommonsWare Jun 25 '13 at 11:23
  • 3
    Unfortunately, I am not a talented programmer, provided I started coding in Android about 4 months ago. Moreover, I don't have a lot of time to adjust the behaviour of the app. Finally, let me just ask a question : is it possible to handle multiple files of different kind with SharedPreferences? – WhiskThimble Jun 25 '13 at 11:41
  • I read this interesting post that suggests to avoid calling system.exit() https://proandroiddev.com/a-cautionary-tale-on-android-do-not-call-system-exit-5279e0d5dbe0 – andrea simeoni Feb 02 '21 at 20:58

7 Answers7

9

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());
alex
  • 5,078
  • 2
  • 31
  • 59
  • I have seen this Blog, but the example isn't clear at this point : what are ACTIVITY and RESTART_INTENT? Where should I declare them so another activity can access them? – WhiskThimble Jun 25 '13 at 12:31
  • Sorry i didn't make the code example clear enough, i fixed it. Is my example now clear to you? – alex Jun 25 '13 at 12:35
  • I already tried this. It closes the application, indeed, but restarts it on the activity that exited it. And that's not what I would like... – WhiskThimble Jun 25 '13 at 12:37
  • Your way totally is the better way to do. Thanks – Huy Tower May 13 '14 at 03:04
  • Android Studio doesn't like this part: getIntent().getFlags() So what should I replace it with? – gonzobrains Jun 18 '14 at 17:15
  • getIntent().getFlags() works fine in Android Studio for me. Since *getFlags()' is available from API level 1 there shouldn't be any problem using it inside e.g. an `Activity`. What kind of error is reported? – alex Jun 19 '14 at 17:17
  • I was having a problem with changes to selected theme via software not propagating correctly through fragments after just finish(); startActivity() and completely restarting like this fixed the problem. – steven smith May 12 '15 at 22:00
  • Your update has solved my problem :). My app is crashing for the first install on marshmallow (https://code.google.com/p/android-developer-preview/issues/detail?id=2965), and I need to restart the app to solve this issue, and don't want the user notice the app is restarting, and your solution is perfect for my case. – Mu Sa Jan 20 '16 at 16:39
  • This is not correct at all. Using the `AlarmManager` to schedule app start intent is restricted by many manufacturers such as Huawei. You better should flush app `Context` or reset bundles instead. – blueware Feb 19 '17 at 10:30
2

This is the newest answer with the latest update 2017 tested and working like a charm hope that help :)

     Intent i = getBaseContext().
               getPackageManager().
          getLaunchIntentForPackage(getBaseContext().getPackageName());
           i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//clear the stack
           i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
           finish();//don`t forget to finish before starting again

                        startActivity(i);//start the activity again
Mohamed Ayed
  • 417
  • 5
  • 7
1

try this

   public void reload() {
     Intent intent = getIntent();
     overridePendingTransition(0, 0);
     intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
     finish();

     overridePendingTransition(0, 0);
     startActivity(intent);
    }
Michael Shrestha
  • 2,467
  • 17
  • 30
1

Solution of AlarmManager can not work because on kill app all pending intents can be removed. On android-10 I have this issue.

But I found other way - create Instrumentation class and call startInstrumentation on Context. Worked very nice.

boolean android.content.Context.startInstrumentation(ComponentName className, String profileFile, Bundle arguments)

Start executing an android.app.Instrumentation class. The given Instrumentation component will be run by killing its target application (if currently running), starting the target process, instantiating the instrumentation component, and then letting it drive the application.

This function is not synchronous -- it returns as soon as the instrumentation has started and while it is running.

Instrumentation is normally only allowed to run against a package that is either unsigned or signed with a signature that the the instrumentation package is also signed with (ensuring the target trusts the instrumentation).

Instrumentation must be defined in manifest. Google how use it.

Enyby
  • 3,484
  • 2
  • 26
  • 35
0

try this code,

public void onClick(DialogInterface dialog, int which) {
    sauvegarde();
    restart(2);
}

restart method

public void restart(int delay) {
    Intent launchIntent = new Intent(context, YourStartUpActivity.class);
    PendingIntent intent = PendingIntent.getActivity(getApplicationContext(), 0, launchIntent , 0);
    AlarmManager manager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    manager.set(AlarmManager.RTC, System.currentTimeMillis() + delay, intent);
    System.exit(2);
}
Stack Overflow User
  • 3,912
  • 6
  • 26
  • 46
0

in your restart activity add this

restart.this.finish();
getActivity(otheractivity.class).finish();
Intent in = new Intent(this,main.class);
startActivity(in);

for each of your activity add getactivity(yourclassname) then finish activity. if you add all your activity like this your application close & restart

er reflex
  • 64
  • 7
0

By Using a Pending Intent You can Restart your Application when you want,Just use the below Lines of code

int pendingId_Intent = 987654;
Intent YourMainActivityIntent = new Intent(Context, YourMainActivity.class);

PendingIntent intentPending = PendingIntent.getActivity(context, 
pendingId_Intent,    YourMainActivityIntent, 
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarm_manager = 
(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarm_manager.set(AlarmManager.RTC, System.currentTimeMillis() + 100, 
intentPending);
System.exit(0);
Nadeem Bhat
  • 982
  • 6
  • 10