Android程序异常崩溃处理

Thread.UncaughtExceptionHandler类用于处理程序未捕获的异常,当程序发生运行时异常就会进入该类的uncaughtException方法进行处理

public class CrashHandler implements Thread.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) {
        System.out.println("异常出现");
// ex.printStackTrace();
        Intent _intent = new Intent(mContext, LoginActivity.class);
        _intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(_intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}

你可能感兴趣的:(程序崩溃,全局异常)