碰到程序崩潰時,閃退效果,不會提示"xxx程序異常,退出程序"。這樣的效果就要使用到未捕獲異常來實現,這裏記錄了我的一個寫法。其實原理很簡單,設置程序的未捕獲異常監聽,實現監聽的一個方法,在該方法中現實直接沒有提示的退出程序。
捕獲異常工具類
package com.tdh.http; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.Thread.UncaughtExceptionHandler; import android.content.Context; import android.util.Log; public class OtherExceptionsHandler implements UncaughtExceptionHandler { private static Context mAppContext; //上下文對象 private static OtherExceptionsHandler instance; //單例引用,這裏我們做成單例的,因爲我們一個應用程序裏面只需要一個UncaughtExceptionHandler實例 private OtherExceptionsHandler(){} public synchronized static OtherExceptionsHandler getInstance(){ //同步方法,以免單例多線程環境下出現異常 if (instance == null){ instance = new OtherExceptionsHandler(); } return instance; } /**需要上下文對象的初始化*/ public synchronized OtherExceptionsHandler init(Context context){ //初始化,把當前對象設置成UncaughtExceptionHandler處理器 Thread.setDefaultUncaughtExceptionHandler(this); mAppContext = context.getApplicationContext(); return instance; } public synchronized OtherExceptionsHandler init(){ //初始化,把當前對象設置成UncaughtExceptionHandler處理器 Thread.setDefaultUncaughtExceptionHandler(this); return instance; } @Override public void uncaughtException(Thread thread, Throwable ex) { if(mAppContext != null){ otherException(thread, ex, mAppContext); } otherException(thread, ex); } /** * 處理異常的一般情況 * @param thread * @param ex */ public void otherException(Thread thread, Throwable ex){ StringWriter sw = new StringWriter(); ex.printStackTrace(new PrintWriter(sw, true)); Log.e("uncaughtException", "thread: " + thread + " name: " + thread.getName() + " id: " + thread.getId() + "exception: " + Log.getStackTraceString(ex)); System.exit(0); } /** * 處理異常的特殊情況,一般是需要用到上下文對象context * @param thread * @param ex * @param context */ public void otherException(Thread thread, Throwable ex, Context context){ } } |
2.在Application中初始化
package com.tdh.http; import android.app.Application; public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); OtherExceptionsHandler.getInstance().init(); } } |
3.在AndroidManifest.xml中配置
<application android:name="com.tdh.http.MyApplication" ... > |
4.在activity中測試
findViewById(R.id.button1).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String e = null; e.getBytes(); } }); |