Transferred from: http://www.cnblogs.com/draem0507/archive/2013/05/25/3099461.html
First, why should crash
Crash can be understood as depravity and downfall. According to our popular understanding, Android App crashes because of unpredictable factors.
Even though our program has undergone a lot of testing before it is released, unexpected crash can occur after countless user usage.
In order to respond to bugs in a timely manner, we usually need a crash mechanism to let developers know the problem as quickly as possible and improve it in the next release.
Second, how to achieve crash
Java has a Uncaughtexceptionhandler interface in thread that is primarily intended to invoke handlers when the thread terminates abruptly because of an uncaught exception.
The interface below has Setdefaultuncaughtexceptionhandler ( Thread.uncaughtexceptionhandler eh)
method, the main function of the method is to set the default handler that is called when the thread is abruptly terminated because it did not catch an exception, and no other handlers are defined for the thread.
The general demo is as follows
Public classDefaultexceptionhandlerImplementsUncaughtexceptionhandler {PrivateContext act =NULL; PublicDefaultexceptionhandler (Context Act) { This. act =Act; } @Override Public voiduncaughtexception (thread thread, Throwable ex) {//collecting exception information and sending it to the serverSendcrashreport (ex); //wait half a second Try{Thread.Sleep (500); } Catch(interruptedexception e) {// } //Handling Exceptionshandleexception (); } Private voidSendcrashreport (Throwable ex) {StringBuffer exceptionstr=NewStringBuffer (); Exceptionstr.append (Ex.getmessage ()); Stacktraceelement[] Elements=Ex.getstacktrace (); for(inti = 0; i < elements.length; i++) {exceptionstr.append (elements[i].tostring ()); } //TODO//send the collected crash information to the server } Private voidhandleexception () {//TODO//the exception can be handled here. //such as prompting the user program crashes. //For example, record important information and try to restore the scene. //or simply record important information and kill the program directly. } }
Called in the main thread
Thread.setdefaultuncaughtexceptionhandler (new Defaultexceptionhandler (this. Getapplicationcontext ()));
have been to the company project Crashhandler class is not very familiar with, here combined with project code, see how the concrete implementation of
First, configure the name in the application node in Androidmanifest.xml
<application Android:name= "COM.NEWLAND.MBOP.APPLICATION.CRASHHANDLERAPP" >
Initialize Crashhandler in Crashhandlerapp (Implementation class to implement Uncaughtexceptionhandler)
@Override Public void onCreate () { = crashhandler.getinstance (); Ch.init (this); Super . OnCreate (); }
Finally, the concrete realization of the Crashhandler class is seen.
Public classCrashhandlerImplementsUncaughtexceptionhandler {/**Get Crashhandler Instance*/ Public StaticCrashhandler getinstance () {if(INSTANCE = =NULL) INSTANCE=NewCrashhandler (); returnINSTANCE; } Public voidInit (Crashhandlerapp app) {log.i ("Baseactivity", "Init ()"); This. App =app; //sets the processor for which the class is the default uncatchexception of the thread. Thread.setdefaultuncaughtexceptionhandler ( This); } /*** When uncaughtexception occurs, the function is recalled to handle*/@Override Public voiduncaughtexception (thread thread, Throwable ex) {System.out.println ("System wrong ...."); //mbopapplication app= (mbopapplication) Maincontext; //App.setneed2exit (TRUE); //Exception Information Collectioncollectcrashexceptioninfo (thread, ex); //Application Information CollectionCollectcrashapplicationinfo (APP); //Save the error report file to the file. Savecrashinfotofile (ex); //Mbopapplication.setcrash (TRUE); //determines whether the UI thread is an exception, Thread.getid () ==1 is the UI thread if(Thread.getid ()! = 1) {//System.out.println ("Exception ThreadId" + Thread.getid ());Thread.Interrupt (); //TODO jump to IndexactivitySystem.out.println ("Thread ID--->" +Thread.CurrentThread (). GetId ());//Intent Intent =new Intent (maincontext,indexactivity.class);//actcontext.startactivity (Intent); //A Popup dialog box prompts the user to upload an exception log to the server NewThread () { Public voidrun () {} {looper.prepare (); NewAlertdialog.builder (App.getcurrentact ()). Settitle ("Exception Handling"). Setmessage ("Your program has an exception, do you want to upload the exception information to the server?").). Setpositivebutton ("Yes",NewOnclicklistener () { Public voidOnClick (Dialoginterface Dialog,intwhich) { NewThread (NewRunnable () {@Override Public voidrun () {sendcrashreportstoserver (app,false); }}). Start ();//New Thread () {//Public void Run () {} {//try{//System.out.println ("Execute Upload thread id" +this.getid ());//This.sleep (the);//}catch (Exception e) {// // }//Sendcrashreportstoserver (app);// }//}.start (); }}). Setnegativebutton ("No",NewOnclicklistener () {@Override Public voidOnClick (Dialoginterface Dialog,intwhich) {}}). Create (). Show (); Looper.loop (); }}.start (); } Else {//Usersessioncache usc=usersessioncache.getinstance ();//ObjectOutputStream oos=null;//try {//Oos.writeobject (USC);//} catch (IOException e) {//e.printstacktrace ();// }//sharedpreferences prefenpreferences = Maincontext//. Getsharedpreferences ("Ismbopcrash", activity.mode_private);//sharedpreferences.editor Editor = Prefenpreferences.edit ();//editor.clear ();//Editor.putboolean ("Iscrash", true);//Editor.commit (); //Scenario One: Drop all activity into the activity list and then cycle through the list to exit the program for(inti = App.getactivitylist (). Size ()-1; I >=0; i--) {Activity Act=app.getactivitylist (). get (i); Act.finish (); } corecommonmethod.setcrash (App,true); Intent Intent=NewIntent (app, welcomeactivity.class); Intent.putextra (Welcomeactivity.extra_direct_to_index,true); Intent.putextra (Welcomeactivity.extra_userinfo, Usersessioncache.getinstance (). GetUserInfo ()); Intent.putextra (welcomeactivity.extra_current_portal_id, Usersessioncache.getinstance (). GetCurrentPortalId ());//intent.setflags (intent.flag_activity_new_task);//app.startactivity (Intent); android.os.Process.killProcess (Android.os.Process.myPid ()); //Scenario Two: Close the application directly using the Activitymanager Restartpackage method,//This method is deprecated after android2.1 and does not work//Activitymanager am = (activitymanager) maincontext.getsystemservice (context.activity_service);//Am.restartpackage (Maincontext.getpackagename ()); } }}
In general, when crash occurs, we need to know the Client SDK version, program version, resolution and other factors
How Android Apps feedback crash reports