Today we have this problem and share the solution.
Android does not have a main function, and naturally there is no solution to add exception handling in main to achieve global exception capture. Does the Android program have a solution for global exception replenishment?
The answer is:
That is, you have to inherit the application from the Android project, such as:
public class Readerapplication extends application implements thread.uncaughtexceptionhandler{...}
and implement the thread exception replenishment interface: Thread.uncaughtexceptionhandler
This way your program, as long as there are no handling exceptions, will be captured in the Uncaughtexception function below. My practice is to restart the application.
@Overridepublic void uncaughtexception (thread thread, Throwable ex) {//TODO auto-generated method stub//system.exit (0) ; Intent Intent = Getbasecontext (). Getpackagemanager (). getlaunchintentforpackage (Getbasecontext (). Getpackagename ()); Pendingintent restartintent = pendingintent.getactivity ( getapplicationcontext (), 0, intent, Intent.flag_ Activity_new_task); Exit program Alarmmanager mgr = (alarmmanager) getsystemservice (context.alarm_service); Mgr.set (ALARMMANAGER.RTC, System.currenttimemillis () + restartintent);//1 seconds after restart application system.exit (0); }
But you have to say that you have to register the exception callback interface in the OnCreate function of application:
Thread.setdefaultuncaughtexceptionhandler (this);
Finally, you have to change this sentence into your own application in the Androidmanifest.xml:
<application
Android:name= "Com.founder.reader.ReaderApplication"
Well, with the above global exception handling, there is no use of the so-called main function can be achieved. At the same time, the program will no longer prompt "XXX software to stop running".
Finally: The program restarts with the system clock to restart, or the program exits, who will perform the restart task:
Alarmmanager mgr = (alarmmanager) getsystemservice (Context.alarm_service); Mgr.set (ALARMMANAGER.RTC, System.currenttimemillis () + restartintent); Restart the app after 1 seconds
Finally, do not forget to make an ad for your own small website: programmer must-have software: www.uhdesk.com