异常退出

I know this question is a bit old, but for future references and googlers, here is a complete answer from another, hard to find, stackoverflow question: Android App Restarts upon Crash/force close


create a class used to handle unCaughtException

public class MyExceptionHandler implements
        java.lang.Thread.UncaughtExceptionHandler {
    private final Context myContext;
    private final Class<?> myActivityClass;

    public MyExceptionHandler(Context context, Class<?> c) {

        myContext = context;
        myActivityClass = c;
    }

    public void uncaughtException(Thread thread, Throwable exception) {

        StringWriter stackTrace = new StringWriter();
        exception.printStackTrace(new PrintWriter(stackTrace));
        System.err.println(stackTrace);// You can use LogCat too
        Intent intent = new Intent(myContext, myActivityClass);
        String s = stackTrace.toString();
        //you can use this String to know what caused the exception and in which Activity
        intent.putExtra("uncaughtException",
                "Exception is: " + stackTrace.toString());
        intent.putExtra("stacktrace", s);
        myContext.startActivity(intent);
        //for restarting the Activity
        Process.killProcess(Process.myPid());
        System.exit(0);
    }
}

Then in every thread (usually you have just one, unless you start a new thread (Async or ... , ofcourse you know about threads if you are able to make new ;) ), set this class as the DefaultUncaughtExceptionHandler

Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this,
            YourCurrentActivity.class));

Remember though!Do it in the very last step of developing your application, you HAVE to at least try handle all of your exceptions one by one before leaving them for DefaultUncaughtExceptionHandler

展开阅读全文

没有更多推荐了,返回首页