Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to auto-restart an application after it has been "force closed"?

Tags:

android

In an Android application, we usually got the "Force Closed" error if we didn't handle the exceptions properly.

How can I restart my application automatically if it is force closed?

Is there any specific permission used for this?

like image 827
Johnny Avatar asked Apr 21 '10 09:04

Johnny


People also ask

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.


1 Answers

To accomplish this you have to do two things:

  1. Avoid the "Force close" - standard way of application crash.
  2. Setup a restart mechanism when the crash happens anyway.

See below how to do these:

  1. Call Thread.setDefaultUncaughtExceptionHandler() in order to catch all uncaught exception, in which case uncaughtException() method will be called. "Force close" will not appear and the application will be unresponsive, which is not a quite good thing. In order to restart your application when it crashed you should do the following :

  2. In the onCreate method, in your main activity initialize a PendingIntent member:

    Intent intent = PendingIntent.getActivity(     YourApplication.getInstance().getBaseContext(),     0,     new Intent(getIntent()),     getIntent().getFlags()); 

Then put the following in your uncaughtException() method:

AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 2000, intent); System.exit(2); 

You also must call System.exit(), otherwise will not work. In this way your application will restart after 2 seconds.

Eventually you can set some flag in your intent that the application crashed and in your onCreate() method you can show a dialog "I'm sorry, the application crashed, hope never again :)".

like image 55
Gyuri Majercsik Avatar answered Oct 22 '22 16:10

Gyuri Majercsik