当前位置: 代码迷 >> Android >> android开发步步为营之57:UncaughtExceptionHandler未捕获的错误处理器
  详细解决方案

android开发步步为营之57:UncaughtExceptionHandler未捕获的错误处理器

热度:85   发布时间:2016-04-28 01:14:23.0
android开发步步为营之57:UncaughtExceptionHandler未捕获的异常处理器

           写程序的时候,大部分的时候,我们都会知道添加try,catch的代码块,比如

   try {            mRoot = inflater.inflate(R.layout.fragment_setting, container, false);            initView(mRoot);        } catch (Exception e) {            log.error("SettingFragment", e);        } catch (OutOfMemoryError e) {            log.error("SettingFragment.OutOfMemoryError", e);        }

          但是有些地方忘记添加的话,就会导致程序奔溃,整个app就停止运行了,就像这样:


            很显然这样的用户体验是很不好的,我们需要避免,这样的话,我们就需要添加一个默认的异常处理程序,在异常发生的时候,能够捕获,给用户一个提示或者跳转到首页去,这样就不至于野蛮的弹出一个程序停止运行的错误。好的,那下面我们开始添加这个默认的异常处理程序,一般在重写的Application类onCreate()里面,即app一旦启动的时候,我们就需要添加进去。

            

 /** *  */package com.figo.study;import java.io.PrintWriter;import java.io.StringWriter;import java.io.Writer;import java.util.ArrayList;import com.figo.study.utils.CrashHandler;import android.app.Activity;import android.app.Application;import android.content.Intent;import android.util.Log;import android.widget.Toast;/** * @author figo * */public class MainApplication extends Application{    @Override    public void onCreate() {        super.onCreate();        //设置Thread Exception Handler        initExHandler();</span>    }     public void initExHandler(){          //设置该CrashHandler为程序的默认处理器            CrashHandler catchExcep = new CrashHandler(this);          Thread.setDefaultUncaughtExceptionHandler(catchExcep);       }  }
        异常处理类CrashHandler.java

package com.figo.study.utils;import java.lang.Thread.UncaughtExceptionHandler;import android.app.AlarmManager;import android.app.PendingIntent;import android.content.Context;import android.content.Intent;import android.os.Looper;import android.util.Log;import android.widget.Toast;import com.figo.study.AActivity;import com.figo.study.MainApplication;public class CrashHandler implements UncaughtExceptionHandler {    private Thread.UncaughtExceptionHandler mDefaultHandler;        public static final String TAG = "CatchExcep";      MainApplication application;            public CrashHandler(MainApplication application){           //获取系统默认的UncaughtException处理器             mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();           this.application = application;      }            @Override      public void uncaughtException(Thread thread, Throwable ex) {              if(!handleException(ex) && mDefaultHandler != null){               //如果用户没有处理则让系统默认的异常处理器来处理                mDefaultHandler.uncaughtException(thread, ex);                        }else{                               Intent intent = new Intent(application.getApplicationContext(), MainActivity.class);              PendingIntent restartIntent = PendingIntent.getActivity(                        application.getApplicationContext(), 0, intent,                        Intent.FLAG_ACTIVITY_NEW_TASK);                                                             //退出当前程序,跳转到首页 MainActivity.class            AlarmManager mgr = (AlarmManager)application.getSystemService(Context.ALARM_SERVICE);                mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,restartIntent); // 1秒钟后重启应用               application.finishActivity();                           }        }            /**       * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.       *        * @param ex       * @return true:如果处理了该异常信息;否则返回false.       */        private boolean handleException(Throwable ex) {            if (ex == null) {                return false;            }            //使用Toast来显示异常信息            new Thread(){                @Override                public void run() {                    Looper.prepare();                    Toast.makeText(application.getApplicationContext(), "很抱歉,程序出现异常,即将退出.",                           Toast.LENGTH_SHORT).show();                             Looper.loop();                    }           }.start();            return true;        }    }


  相关解决方案