android捕获异常并处理
利用Thread.UncaughtExceptionHandler 获取异常,并对异常做出处理:
application代码:
public class TestApplication extends Application{
??? public void onCreate(){
??????? TestException testException = TestException.getInstance();?
??????? testException.init(getApplicationContext());
??? }
}
exception代码:
public class TestException? implements UncaughtExceptionHandler {
??? //获取application 对象;
??? private Context mContext;
???
??? private Thread.UncaughtExceptionHandler defaultExceptionHandler;
??? //单例声明TestException;
??? private static TestException? testException;
???
??? private TestException(){???????
??? }
???
??? public static TestException? getInstance(){
??????? if(testException == null){?
??????????? testException = new TestException? ();
??????? }
??????? return testException ;
??? }
???
??? @Override
??? public void uncaughtException(Thread thread, Throwable exception) {
??????? // TODO Auto-generated method stub
??????? if(defaultExceptionHandler != null){
???????????
??????????? Log.e("tag", "exception >>>>>>>"+exception.getLocalizedMessage());
??????????? //将异常抛出,则应用会弹出异常对话框.这里先注释掉
//??????????? defaultExceptionHandler.uncaughtException(thread, exception);
??????????? android.os.Process.killProcess(android.os.Process.myPid());
??????????? System.exit(10);
??????? }
??? }
???
???? public void init(Context context) {??
??????????? mContext = context;??
??????????? defaultExceptionHandler? = Thread.getDefaultUncaughtExceptionHandler();??
?????????? Thread.setDefaultUncaughtExceptionHandler(this);??
????????? }
}
?
在TestManifest.xml中配置:
<application
??????? android:name="com.test.TestApplication"
??????? android:label="@string/app_name" >