Android program crash processing

Source: Internet
Author: User
Tags dateformat

Reprint please specify the source: http://blog.csdn.net/allen315410/article/details/41444053

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;public class MainActivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); int i = 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;public class Crashhandler implements Uncaughtexceptionhandler {public static final String TAG = "Cra Shhandler ";//system default Uncaughtexception processing class private Thread.uncaughtexceptionhandler mdefaulthandler;// Crashhandler instance private static Crashhandler INSTANCE = new Crashhandler ();//Program Context object private Context mcontext;// Used to store device information and exception information PrivaTe map<string, string> infos = new hashmap<string, string> ();//For formatting dates, as part of the log file name private DateFormat Formatter = new SimpleDateFormat ("Yyyy-mm-dd-hh-mm-ss");/** guarantees only one Crashhandler instance */private Crashhandler () {}/** Get Crashhandler instance, Singleton mode */public static Crashhandler getinstance () {return INSTANCE;} /** * Initialize * * @param context */public void init (context context) {Mcontext = context;//get system default Uncaughtexception processor Mdefau Lthandler = 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 */@Overridepublic void uncaughtexception (thread thread, Throwable ex) {if (! HandleException (ex) && Mdefaulthandler! = null) {//If the user does not handle it, let the system default exception handler handle the Mdefaulthandler.uncaughtexception (thread, ex);} else {try {thread.sleep,} 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 errorsInformation about sending error reports is done here. * * @param ex * @return true: Returns False if the exception information is processed; */private boolean handleexception (Throwable ex) {if (ex = = null) {return false;} Use Toast to display exception information new Thread () {@Overridepublic void run () {looper.prepare (); Toast.maketext (Mcontext, "Sorry, the program has an exception and is about to exit.", Toast.length_long). Show (); Looper.loop ();}}. Start ();//Collect equipment parameter information collectdeviceinfo (mcontext);//Save log file Savecrashinfo2file (ex); return true;} /** * Collect device parameter information * * @param ctx */public void Collectdeviceinfo (Context ctx) {try {packagemanager pm = ctx.getpackagemanage R (); 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 if 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 */private String Savecrashinfo2file (Throwable ex) {Stringbuff ER 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 (new Date ()); String fileName = "crash-" + Time + "-" + timestamp + ". Log"; if (EnvironMent.getexternalstoragestate (). Equals (environment.media_mounted)) {String path = "/sdcard/crash/"; File dir = new file (path), if (!dir.exists ()) {dir.mkdirs ();} FileOutputStream fos = 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;public Class Crashapplication extends application {@ overridepublic void OnCreate () {//TODO auto-generated method Stubsuper.oncreate (); Crashhandler Crashhandler = 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= ". Crashapplication "...>    ..... </application>

To configure SDcard Write file permissions:

<uses-permission 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 to start Activity componentinfo{com.example.crash/ Com.example.crash.MainActivity}:         java.lang.ArithmeticException:divide by zero ... caused by:java.lang.ArithmeticException:divide by zeroat Com.example.crash.MainActivity.onCreate (Mainactivity.java : @ android.app.Activity.performCreate (activity.java:5243) at Android.app.Instrumentation.callActivityOnCreate (instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity (activitythread.java:2140) ... 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.