Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force application to restart on first activity

Tags:

android

For an unknown reason, I can't get my application leaving properly so that when I push the home button and the app icon again, I resume where I was in the app. I would like to force the application to restart on the first Activity.

I suppose this has something to do with onDestroy() or maybe onPause() but I don't know what to do.

like image 956
Sephy Avatar asked Mar 18 '10 15:03

Sephy


People also ask

How do you start an activity only once the app is opened for the first time?

It is important to check that the first activity which opens when the app is launched is MainActivity. java (The activity which we want to appear only once). For this, open the AndroidManifest. xml file and ensure that we have the intent-filter tag inside the activity tag that should appear just once.

How do I automatically restart apps on Android?

In order to restart your application when it crashed you should do the following : In the onCreate method, in your main activity initialize a PendingIntent member: Intent intent = PendingIntent. getActivity( YourApplication.


2 Answers

Here is an example to restart your app in a generic way by using the PackageManager:

Intent i = getBaseContext().getPackageManager()              .getLaunchIntentForPackage( getBaseContext().getPackageName() ); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(i); 
like image 66
Marc Avatar answered Sep 20 '22 00:09

Marc


The solution marked as 'answer' works but has one disadvantage that was critical for me. With FLAG_ACTIVITY_CLEAR_TOP your target activity will get onCreate called before your old activity stack receives onDestroy. While I have been clearing some necessary stuff in onDestroy I had to workaroud.

This is the solution that worked for me:

public static void restart(Context context, int delay) {     if (delay == 0) {         delay = 1;     }     Log.e("", "restarting app");     Intent restartIntent = context.getPackageManager()             .getLaunchIntentForPackage(context.getPackageName() );     PendingIntent intent = PendingIntent.getActivity(             context, 0,             restartIntent, Intent.FLAG_ACTIVITY_CLEAR_TOP);     AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);     manager.set(AlarmManager.RTC, System.currentTimeMillis() + delay, intent);     System.exit(2); } 

The idea is to fire a PendingIntent via AlarmManager that will be invoked a bit later, giving old activity stack some time to clear up.

like image 20
AAverin Avatar answered Sep 21 '22 00:09

AAverin