android全局捕获异常,重启应用

1.捕获异常类
public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private Context context;
    public CrashHandler(Context context){
        this.context=context;
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        showToast(t);
    }

    /**
     * 操作
     * @param thread
     */
    private void showToast(Thread thread) {
        final Dialog dialog=new Dialog(context);
        dialog.setContentView(R.layout.dialog_layout);

        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(context, "程序异常,重新启动", Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        }).start();

        try {
            thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        restartApp();
    }

    /**
     * 重启应用
     */
    private void restartApp(){
        Intent intent = new Intent(context,MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());//再此之前可以做些退出等操作
    }
}
2.自定义Application
public class MyApplication extends Application {
    private static Context mContext;
    @Override
    public void onCreate() {
        super.onCreate();
        mContext=this;
        Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(mContext));
    }
}

3.manifest里面内容



    
        
            
                

                
            
        
        
    





你可能感兴趣的:(android全局捕获异常,重启应用)