Handwritten Crashhandler implements Uncaughtexceptionhandler to intercept Android anomalies

Source: Internet
Author: User
<span id="Label3"></p>Handwritten Crashhandler implements Uncaughtexceptionhandler to intercept Android anomalies<p><p>Code word Clerk Small D</p></p><p><p>It's a bit complicated, although I know the principle, but it's not good to start with.</p></p><p><p>First this is an object that needs to be present throughout the App's running state, so you need to initialize the class in application, and this class instance is slow! Find the code in doubt, application only in the OnCreate method inside the initialization</p></p><pre><pre><code>public class CrashApplication extends Application {@Overridepublic void onCreate() { super.onCreate();// CrashHandler crashHandler = CrashHandler.getInstance(); CrashHandler crashHandler = new CrashHandler(); crashHandler.init(getApplicationContext());}}</code></pre></pre><p><p>There is no instance of this Uncaughtexceptionhandler in application (crashhandler implements the Uncaughtexceptionhandler interface class); just doing the initialization work here, The Uncaughtexceptionhandler class can be used to intercept any uncaught exceptions that the app runs from the Start.</p></p><p><p>The write Crashhandler class can be written in a single case, or it can be a direct new object. In fact, I think the singleton here is not necessary, directly new an object, the object is to be set to the thread class anyway</p></p><pre><pre><code>/** * Sets the default uncaught exception handler. This handler is invoked in * case any Thread dies due to an unhandled exception. * * @param handler * The handler to set or null. */public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler) { Thread.defaultUncaughtHandler = handler;}</code></pre></pre><p><p>The above thread.defaultuncaughthandler is a static instance of the System. Now understand the fact that it is not necessary to maintain a singleton object outside with static, a singleton object is maintained in the System.</p></p><p><p>All right, Let's write the two methods of initializing Crashhandler and direct new in a single case.</p></p><pre><pre><code>/** 保证只有一个CrashHandler实例 */public CrashHandler() {}//CrashHandler实例private static CrashHandler INSTANCE = new CrashHandler();/** 获取CrashHandler实例 ,单例模式 */public static CrashHandler getInstance() { return INSTANCE;}</code></pre></pre><p><p>What we need to discuss here is how to implement the interception Exception. In fact, there are anomalies in the Android system will be error, Flash back, application not response ANR. What we have to do is to share the task of the system for our default handling of Exceptions. The system default processing exception is not friendly, Half-day does not respond, the return key also useless, finally will pop up a window to want the user to decide whether to end or wait.</p></p><p><p>Look at the source code of the thread in android, you can see, there is a</p></p><pre><pre><code>public class ThreadGroup implements Thread.UncaughtExceptionHandler{</code></pre></pre><p><p>Implements the thread inside the Uncaughtexceptionhandler interface, This class has the system thread Group ... well, The system code is not very good.</p></p><pre><pre><code>//获取系统默认的UncaughtException处理器 mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();</code></pre></pre><p><p>We need to get the default Defaultuncaughthandler of the System. But the question is who the Defaultuncaughthandler is initialized or set in the past, and there is no initialization process in the thread class. The system should be set to initialize the past, temporarily did not find specific code implementation ... You know, teach me!</p></p><p><p>then, we need to set our own Uncaughtexception class to the system variable Defaultuncaughthandler.</p></p><pre><pre><code>//设置该CrashHandler为程序的默认处理器 Thread.setDefaultUncaughtExceptionHandler(this);</code></pre></pre><p><p>Ok, It's a little messy here, actually. Taken care, first we need to get a system default exception handling object defaultuncaughthandler, then we want to set the system default exception handling object to our own write an implementation uncaughtexception interface Object. Why did you do it?</p></p><p><p>First the system default exception handling object Defaultuncaughthandler maintains a system exception handling object, obtains to this system processing object can by call Uncaughtexception (thread, ex), The method realizes the system default exception Processing.</p></p><p><p>and we're going to write our Own. an object that implements the Uncaughtexception interface is set to the system default Exception-handling object so that the system detects that an unhandled exception is called our own implementation of the Uncaughtexception (thread, Ex) method. The processing logic is then implemented in this Method.</p></p><p><p>Taken care know that we need to implement the processing logic within the Uncaughtexception method of the Crashhandler class that implements the Uncaughtexception Interface. And after you have completed your own processing logic, you perform the system principle by default handling of Uncaught Exceptions.</p></p><p><p>PS: Why do you have to let the system default exception handling after processing the object again, because the system defaults to exception handling has a default processing scheme, such as runtimeexcption runtime exception, nullexception null pointer exception how to Handle. In fact, all the cards are dead, and then the window lets the user decide how to deal with, wait or end. This pop-up window of two options, the user chose to wait, indicating that the state of the card is normal, perhaps the network request is slow but it is true that logic is Responsible. The user chooses the end, stating that this is indeed an exception to be immediately ended. The end of the selection is that the user selects the system default exception handling, that is, called a similar defaultuncaughthandler.uncaughtexception (thread, Ex) method Processing.</p></p><pre><pre> <code>/** * 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 Mdefaulthandl Er.uncaughtexception (thread, ex);//mdefaulthandler.uncaughtexception (null, ex);//android.os.Process.killPr Ocess (android.os.Process.myPid ());//system.exit (0); } 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 (0); }}</code></pre></pre><p><p>The HandleException (ex) of the callback interface method here is our custom handling of the Exception. Let's not think about it.<br>In fact, this simulates the default exception handling of the system, that is, when there is no default exception handling, the thread sleeps for 3 seconds and then exits the app. Equivalent to three seconds of card death and then the window to remind users to Choose.<br>After handling the unhandled exception handling by default, the default exception handling object processing is Exited.<br>but, Here I found that if it is mdefaulthandler.uncaughtexception (thread, ex), the first time the processing is normal exit application, when the second click on the app icon is not executed to our own handling of the exception method. The third time you click on the app icon pops up our exception handling Method. What is this for? My point of view is that the system has a cache exception mechanism, the same as the task of the same error processing, it will no longer execute our own written exception handling, the direct exit. This is my point of view. To refute Criticism.<br>So I let mdefaulthandler.uncaughtexception (null, ex), and one of the arguments is null, the system will not cache the record exception, because it is null, no exception AH ~ am I flirting with the system? So every time, we can execute our processing method normally.<br>Of course you can also write our own exception handling methods in the system handling exception Mode. But if the end does not quit the application will be stuck,,,,, in <strong>fact, here personally more recommend themselves write Android.os.Process.killProcess (android.os.Process.myPid ()); If you pass a null to the system default exception handling will report a null pointer exception ~ ~</strong></p></p><p><p>Let's talk about how we handled the ANOMALY.</p></p><pre><pre> <code>/** * Custom error handling, collect error messages to send error reports, and so On. * * @param ex * @return True: If the exception information is processed; otherwise, false is Returned. */private Boolean hand Leexception (throwable Ex) {if (ex = = Null) {return false; }//use Toast to display exception information new Thread () {@Override public void run () {looper.prepare (); Toast.maketext (mcontext, "error ~ ~ ~ ~", toast.length_long). Show (); Testservice.getinstance (). senderror ("error:made by byl"); Looper.loop (); }}.start (); Collect equipment parameter information Collectdeviceinfo (mcontext); Save log file Savecrashinfo2file (ex); return false;} </code> </pre></pre><p><p>Collect equipment parameter information Collectdeviceinfo (mcontext);<br>Save log file Savecrashinfo2file (ex);<br>There are two ways to do This. Save the error log. I think similar to Umeng this kind of error analysis of the system must also be handled, otherwise you can know what the cell phone error statistics are clear.<br>Here the key is in Testservice this backstage service.<br>By the way, Here's the Looper.prepare and looper.loop method. online talk toast to display in a child line, a message queue (Looper) must exist in the current Thread. Specific handler operation, you see the toast source will Know. All right <del>~<br><br>Hate the interview a lot of people ask handler ah, Looper object ah, Message Queue ah, and then I will be very general said Android Looper is a polling class, handler each time send a message will put the message in the message queue , and then looper to poll this message queue to go to one of the processing Messages. In fact, I can understand that this layer, specifically how to poll, how to deal with the actual code of the message how to implement I do not know AH</del> ~ believe that many interviewers are not clear!<br></p></p><pre><pre><code></code></pre></pre><p><p>Testservice is a service, and when the first activity starts, it</p></p><pre><pre><code>Intent intent = new Intent(this, TestService.class); startService(intent);</code></pre></pre><p><p>The backend service silently waits for the system to catch an uncaught exception and then executes its own method</p></p><pre><pre><code> Intent intent = new Intent(this, SendErrorActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("msg", message); startActivity(intent); stopSelf();</code></pre></pre><p><p>Then this senderroractivity can realize the function of the popup window prompt, the concrete logic depends on the business demand.<br>Let's talk about the concrete implementation of this Senderroractivity.<br>Manifest inside Configuration</p></p><pre><pre><code><activity android:name="com.example.testerror.SendErrorActivity" android:screenOrientation="portrait" android:theme="@style/bklistDialog" > </activity></code></pre></pre><p><p>Style inside Configuration Bklistdialog</p></p><pre><pre><code><style name="bklistDialog" parent="@android:style/Theme.Dialog"> <item name="android:windowFrame">@android:color/transparent</item> <item name="android:windowIsFloating">true</item> <item name="android:windowIsTranslucent">true</item> <item name="android:windowNoTitle">true</item> <item name="android:windowBackground">@android:color/transparent</item> <!--控制灰度的值,当为1时,界面除了我们的dialog内容是高亮显示的,dialog以外的区域是黑色的,完全看不到其他内容,系统的默认值是0.5,而已根据自己的需要调整--> <item name="android:backgroundDimAmount">0.3</item> <item name="android:windowAnimationStyle">@null</item></style></code></pre></pre><p><p>Layout file</p></p><pre><code><?xml version= "1.0" encoding= "utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "android:layout_width=" fill_parent "android:layout_height=" fill_parent "android:layout_marginleft=" 25DP " android:layout_marginright= "25dp" ><linearlayout android:layout_width= "fill_parent" android:layout_height= " Wrap_content "android:layout_centerinparent=" true "android:background=" #ffffff "android:gravity=" Center "andro id:orientation= "vertical" > <linearlayout android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:orientation= "vertical" android:padding= "10dp" > <textview and Roid:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_gravity= "center _horizontal "android:padding=" 10dp "android:text=" prompt "android:textsize=" 18sp "/> <textview android:layout_width= "wRap_content "android:layout_height=" wrap_content "android:layout_marginbottom=" 3DP "andro id:text= "do you want to send an error message?" android:textcolor= "#A19D94" android:textsize= "16sp"/> <textview android:id= "@+id/info_ Time "android:layout_width=" wrap_content "android:layout_height=" wrap_content "android:la yout_marginbottom= "10dp" android:textcolor= "#A19D94" android:textsize= "16sp"/> </linearlay out> <linearlayout android:layout_width= "fill_parent" android:layout_height= "wrap_content" A ndroid:orientation= "horizontal" > <button android:id= "@+id/ok" android:layout_width= "fi Ll_parent "android:layout_height=" 45DP "android:layout_weight=" 1 "android:gravity=" Center "android:padding=" 10dp "android:text=" OK "android:textsize=" 18sp "/> &Lt Button android:id= "@+id/cancel" android:layout_width= "fill_parent" android:layout_height= "45dp" android:layout_weight= "1" android:gravity= "center" android:padding= "10dp" android:text= "cancel" android:textsize= "18sp"/> </linearlayout></linearlayout></relativela Yout></code></pre><p><p>Senderroractivity inside the OnCreate method to achieve the specific</p></p><pre><pre><code>@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_loginoutinfo); //全屏显示 getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); ok=(Button) findViewById(R.id.ok); cancel=(Button) findViewById(R.id.cancel); error_msg=getIntent().getStringExtra("msg"); ok.setOnClickListener(this); cancel.setOnClickListener(this);}</code></pre></pre><p><p>OK, It took me two hours to write down this thing. it's worth it to study it. Pure hand knocks ah, trouble Gao Enlighten ah! Thank you</p></p> <p><p>Handwritten Crashhandler implements Uncaughtexceptionhandler to intercept Android anomalies</p></p></span>

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.