android開發步步為營之57:UncaughtExceptionHandler未捕獲的異常處理器

來源:互聯網
上載者:User

標籤:uncaughtexceptionhan   未捕獲的程式異常處理   

           寫程式的時候,大部分的時候,我們都會知道添加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;        }    }


android開發步步為營之57:UncaughtExceptionHandler未捕獲的異常處理器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.