Android program crash processing

Source: Internet
Author: User
Tags dateformat terminates

Android program crash processingtime 2014-11-24 13:45:37 csdn Blog Original http://blog.csdn.net/allen315410/article/details/41444053 ThemeAndroid

In the actual project development, there will be a lot of anomalies directly lead to the program crash out, in the development we can view the error log through Logcat, debug anomalies, let the program safe operation, but in the development of some abnormal hidden deep, until the project was released, due to various reasons, For example, the Android device is inconsistent, and so on, the Android version is different, in fact, we can not be tested in the market on all Android devices are tested, when the user installation is exposed, causing the program to crash out directly, which is obviously not OK for the user! These causes crash on the user device the exception we do not know, in order to know some of these abnormal information, we still have to catch the exception ourselves through the program, and record it (local save or upload server), to facilitate project maintenance.

Let's take a look at the exception I've defined myself "intentionally" in Mainactivity,java:

Package Com.example.crash; import Android.os. Bundle; import Android.app. Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (1;  System.out.println (i/0);}}          

The above procedure reported a mathematical operation except 0 exception, obviously the program was "crashed", can not continue to execute. Look at the effect of the operation:

Running results as shown, this direct crash effect for the user is very not OK, the user does not know what happened, the program stopped, will let the user do not want to continue to use the idea of the program. What can we do with an uncaught exception in the program? What we need is the software has a global exception trap, when there is an exception we did not find, catch the exception, and record the exception information, upload to the server public development This analysis of the specific reasons for the exception, this is a best practice, then we must be familiar with the two categories, One is Android-provided application and the other is Java-provided thread.uncaughtexceptionhandler.

Application: This is the class that the Android program manages the global state, application is created first when the program starts, it is used to manage the activity, service, Broadcastreceiver, ContentProvider four components as well as other Android elements, here you can open the Android project under the Mainifest.xml file to view. In addition to using the Android default application to process programs, we can also customize a application to handle some operations that need to be programmed in a global state, such as a best practice when the handler unknown exception is mentioned in this article.

Thread.uncaughtexceptionhandler: As for the explanation of this concept, I found some scientific explanations in JDK1.6 's documentation.

Invokes the interface of the handler when the Thread terminates abruptly because of an uncaught exception.
When a thread is about to terminate because of an uncaught exception, the Java virtual machine uses Thread.getuncaughtexceptionhandler () to query the thread for its Uncaughtexceptionhandler threads and invokes the handler's The Uncaughtexception method, which passes threads and exceptions as parameters. If a thread does not explicitly set its Uncaughtexceptionhandler, its Threadgroup object is used as its uncaughtexceptionhandler. If the Threadgroup object has no special requirements for handling exceptions, it can forward the call to the default uncaught exception handler.

Thread.uncaughtexceptionhandler is an interface that provides the following methods for customizing handlers.

void Uncaughtexception (Thread t,throwable e)

This method is called when a given thread terminates due to a given uncaught exception. The Java virtual machine ignores any exceptions thrown by the method. Parameters: T-thread E-exception

In a word, the thread did not catch the exception handler to handle the uncaught exception. If the program has an uncaught exception, the dialog box is forced to close on the system by default. We need to implement this interface and register the exception handling as not caught by default in the program. This allows you to do some personalized exception handling when an uncaught exception occurs. So what we're going to do is to customize a Crashhandler class to implement Thread.uncaughtexceptionhandler and do some of the relevant things in the way we implement it.

Package Com.example.crash;Import Java.io.File;Import Java.io.FileOutputStream;Import Java.io.PrintWriter;Import Java.io.StringWriter;Import Java.io.Writer;Import Java.lang.Thread.UncaughtExceptionHandler;Import Java.lang.reflect.Field;Import Java.text.DateFormat;Import Java.text.SimpleDateFormat;Import Java.util.Date;Import Java.util.HashMap;Import Java.util.Map;Import Android.content.Context;Import Android.content.pm.PackageInfo;Import Android.content.pm.PackageManager;Import android.content.pm.PackageManager.NameNotFoundException;Import Android.os.Build;Import android.os.Environment;Import Android.os.Looper;Import Android.util.Log;Import Android.widget.Toast;PublicClass CrashhandlerImplements Uncaughtexceptionhandler {PublicStatic finalString TAG ="Crashhandler";system default Uncaughtexception Processing classPrivate Thread.uncaughtexceptionhandler Mdefaulthandler;Crashhandler instancesPrivatestatic Crashhandler INSTANCE =New Crashhandler ();Context object for the programPrivate Context Mcontext;Used to store device information and exception informationPrivate map<String,string> infos =New hashmap<String,String> ();Used to format the date as part of the log file namePrivate DateFormat Formatter =New SimpleDateFormat ("Yyyy-mm-dd-hh-mm-ss");/** guaranteed only one Crashhandler instance */Private Crashhandler () {}/** get Crashhandler instance, Singleton mode */PublicStatic Crashhandler getinstance () {return INSTANCE;}/** * Initialize * * @param context */PublicVOID init (Context context) {Mcontext = context;Gets the system default Uncaughtexception processor Mdefaulthandler = Thread.getdefaultuncaughtexceptionhandler ();Set the Crashhandler as the program's default processor Thread.setdefaultuncaughtexceptionhandler (this);}/** * When uncaughtexception occurs, it is transferred to the function to process */@OverridePublicvoid Uncaughtexception (thread thread, Throwable ex) {if (!handleexception (ex) && Mdefaulthandler! =NULL) {Let the system default exception handler handle mdefaulthandler.uncaughtexception (thread, ex) if the user does not handle it;}else {try {thread.sleep (3000);}catch (Interruptedexception e) {log.e (TAG,"Error:", e);}Exit Program Android.os.Process.killProcess (Android.os.Process.myPid ()); System.exit (1);}}/** * Custom error handling, collect error messages to send error reports, etc. are done here. * * @param ex * @return true: Returns False if the exception information is processed; */PrivateBoolean handleexception (Throwable ex) {if (ex = =NULL) {Returnfalse;}Use Toast to display exception informationNew Thread () {@OverridePublicvoid Run () {looper.prepare (); Toast.maketext (Mcontext,"Sorry, the program is out of the ordinary and is about to exit.", Toast.length_long). Show (); Looper.loop ();}}. Start ();Collect equipment parameter information collectdeviceinfo (MCONTEXT);Save log file Savecrashinfo2file (ex);Returntrue;}/** * Collect device parameter information * * @param CTX */Publicvoid Collectdeviceinfo (Context ctx) {try {packagemanager pm = Ctx.getpackagemanager (); PackageInfo pi = pm.getpackageinfo (Ctx.getpackagename (), packagemanager.get_activities);if (pi! =NULL) {String Versionname = Pi.versionname = =Null?"NULL": Pi.versionname;String Versioncode = Pi.versioncode +""; Infos.put ("Versionname", Versionname); Infos.put ("Versioncode", Versioncode);}}catch (Namenotfoundexception e) {log.e (TAG,"An error occured when collect package info", e);} field[] fields = Build.class.getDeclaredFields ();for (Field field:fields) {try {field.setaccessible (true); Infos.put (Field.getname (), Field.get (NULL). ToString ()); LOG.D (TAG, field.getname () +":" + field.get (null));}catch (Exception e) {log.e (TAG,"An error occured when collect crash info", e);}}}/** * Save error message to file * * @param ex * @return return file name for easy Transfer of file to server */PrivateString Savecrashinfo2file (Throwable ex) {StringBuffer SB =New StringBuffer ();for (map.entry<String,String> Entry:infos.entrySet ()) {String key = Entry.getkey ();String value = Entry.getvalue (); Sb.append (key +"=" + value +"\ n");} Writer writer =New StringWriter (); PrintWriter PrintWriter =New PrintWriter (writer); Ex.printstacktrace (PrintWriter); Throwable cause = Ex.getcause ();while (cause! =NULL) {cause.printstacktrace (printwriter); cause = Cause.getcause ();} Printwriter.close ();String result = Writer.tostring (); Sb.append (result);try {long timestamp = System.currenttimemillis ();String time = Formatter.format (Newdate ()); string fileName =  "crash-" + Time +  -"+ timestamp + ". Log "; String Path =  "/sdcard/crash/"; File dir = new file (path); new fileoutputstream (path + fileName); Fos.write (Sb.tostring (). GetBytes ()); Fos.close ();} return fileName;} catch (Exception e) {log.e (TAG,  "An error occured while writing File ... ", e);} return null;}         

After completing this Crashhandler class, you also need to customize a global application to start the management exception collection, which is the custom application class, which is simple:

Package Com.example.crash; import Android.app. application {@Overridepublic void OnCreate () {//TODO auto-generated method Stubsuper.oncreate ();  Crashhandler.getinstance (); Crashhandler.init (Getapplicationcontext ());}}     

Finally, in order for the program to use our custom application at startup, we must declare our custom application on the application node of Mainifest.xml:

<application        android:name=      ...>    ..... </application>    

To configure SDcard Write file permissions:

<android:name="Android.permission.WRITE_EXTERNAL_STORAGE"/> 

Run the following program:

Locate the crash folder in the SD card and open the folder:

Everywhere this log logs, open with Notepad, view the content as follows:

Time=1385535270000......java.lang.runtimeexception:unable toStart Activity componentinfo{com.example.crash/com.example.crash.mainactivity}: Java.lang.ArithmeticException:  Divideby Zero ... caused by:java.lang.arithmeticexception:divide by Zeroat com.example.crash.MainActivity.onCreate (Mainactivity.java:13) at android.app.Activity.performCreate (Activity.java:5243) Span class= "Hljs-keyword" >at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity ( Activitythread.java:2140) ... 11 morejava.lang.ArithmeticException:divide by Zeroat com.example.crash.MainActivity.onCreate (Mainactivity.java:13) ......

Well, the program is not caught in time to catch the exception is captured in the SD card, and give users a good hint of information, was not suddenly crash off, through the SD card error log, we can quickly define the source of the error, convenient for us to timely correction of the program. Of course, here I do is a demo, so the related error log is only saved on the SD card, in fact, the good practice is to upload the error log to the server, so that we collect from all sides of the user's log, for the program to update the iteration upgrade.

Note: This article is my study notes, there will be some bugs. The program is only as a reference instance, can not be used directly to the real project, please understand!

Reference: http://www.cjsdn.net/Doc/JDK60/java/lang/Thread.UncaughtExceptionHandler.html

Http://www.cnblogs.com/draem0507/archive/2013/05/25/3099461.html

http://blog.csdn.net/liuhe688/article/details/6584143

Android program crash processing

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.