Android系統的“程序異常退出”,給應用的用戶體驗造成不良影響。為了捕獲應用運行時異常並給出友好提示,便可繼承UncaughtExceptionHandler類來處理。通過Thread.setDefaultUncaughtExceptionHandler()方法將異常處理類設置到線程上即可。
1、異常處理類,代碼如下:
[java]
- public class CrashHandler implements UncaughtExceptionHandler {
- public static final String TAG = CrashHandler;
- private static CrashHandler INSTANCE = new CrashHandler();
- private Context mContext;
- private Thread.UncaughtExceptionHandler mDefaultHandler;
-
- private CrashHandler() {
- }
-
- public static CrashHandler getInstance() {
- return INSTANCE;
- }
-
- public void init(Context ctx) {
- mContext = ctx;
- mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
- Thread.setDefaultUncaughtExceptionHandler(this);
- }
-
- @Override
- public void uncaughtException(Thread thread, Throwable ex) {
- // if (!handleException(ex) && mDefaultHandler != null) {
- // mDefaultHandler.uncaughtException(thread, ex);
- // } else {
- // android.os.Process.killProcess(android.os.Process.myPid());
- // System.exit(10);
- // }
- System.out.println(uncaughtException);
-
- new Thread() {
- @Override
- public void run() {
- Looper.prepare();
- new AlertDialog.Builder(mContext).setTitle(提示).setCancelable(false)
- .setMessage(程序崩潰了...).setNeutralButton(我知道了, new OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- System.exit(0);
- }
- })
- .create().show();
- Looper.loop();
- }
- }.start();
- }
-
- /**
- * 自定義錯誤處理,收集錯誤信息 發送錯誤報告等操作均在此完成. 開發者可以根據自己的情況來自定義異常處理邏輯
- *
- * @param ex
- * @return true:如果處理了該異常信息;否則返回false
- */
- private boolean handleException(Throwable ex) {
- if (ex == null) {
- return true;
- }
- // new Handler(Looper.getMainLooper()).post(new Runnable() {
- // @Override
- // public void run() {
- // new AlertDialog.Builder(mContext).setTitle(提示)
- // .setMessage(程序崩潰了...).setNeutralButton(我知道了, null)
- // .create().show();
- // }
- // });
-
- return true;
- }
- }
2、線程綁定異常處理類
[java]
- public class CrashHandlerActivity extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- CrashHandler crashHandler = CrashHandler.getInstance();
- crashHandler.init(this); //傳入參數必須為Activity,否則AlertDialog將不顯示。
- // 創建錯誤
- throw new NullPointerException();
- }
- }