`
javasss
  • 浏览: 65637 次
  • 性别: Icon_minigender_1
  • 来自: 河南
社区版块
存档分类
最新评论

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" >

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics