tags:

views:

685

answers:

2

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

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

Is there any specific permission is used for this?

+2  A: 

The trick is make sure it doesn't Force Close in the first place.

If you use the Thread.setDefaultUncaughtExceptionHandler() method you can catch the Exceptions that are causing your application to Force Close.

Have a look at this question for an example of using an UncaughtExceptionHandler to log the Exceptions raised by an application.

Dave Webb
Thanks for the clue.A following up question is when would the UncaughtExceptionHandler.uncaughtException be called?If user didn't click the "Force Close" button, will the UncaughtExceptionHandler.uncaughtException still be called?
Johnny
@Johnny You get a Force Close when the application raises an Exception that isn't handled. If you use an UncaughtExceptionHandler then your application can handle all its Exceptions and the user will never see the Force Close dialog. In other words the UncaughtExceptionHandler is called when the Force Close dialog would have been displayed. However, you will want to be careful how you handle any unexpected Exceptions that you application catches; carrying on and pretending nothing happened is obviously risky.
Dave Webb
@Dave Thanks for the explanation. It explains well about the UncaughtExceptionHandler.But I've seen applications that will auto-restart after force-closed. Eg. Launcher(maybe not a good example, but I've seen third-party apps works this way as well). What if I want my app work like this? Do I have to use some kind of system permissions?
Johnny
A: 

In case you call Thread.setDefaultUncaughtExceptionHandler() will allways enter in uncaughtException() in case your application crashed. "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 thing :

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

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

Than in your uncaughtException() method:

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

Without calling System.exit() will not work. This code will restart your application 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 :)".

Gyuri