Android 台灣中文網
標題:
android捕獲全局異常和處理
[打印本頁]
作者:
暗桌之光
時間:
2011-6-14 17:39
標題:
android捕獲全局異常和處理
在做項目時,經常會把錯誤利用異常拋出去,這樣在開發時就可以通過手機拋的異常排查錯誤,很方便。但是當程序開發完畢,版本穩定,需要上線時,為了避免拋出異常影響用戶感受,可以捕獲全局異常,對異常做出處理。
具體的實方法如下:
利用Thread.UncaughtExceptionHandler 獲取異常,並對異常做出處理:
public class MyUncaughtExceptionHandler implements
Thread.UncaughtExceptionHandler {
private Thread.UncaughtExceptionHandler a;
MyUncaughtExceptionHandler(){
this.a = Thread.getDefaultUncaughtExceptionHandler();
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
Log.i("huilurry","ppppppppppppp="+ex.getMessage());
//是否拋出異常
// if(a!=null)
// a.uncaughtException(thread, ex);
}
}
複製代碼
具體調用:
public class HuiLurryActivty extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String t=android.provider.Settings.System.getString(getContentResolver(), "android_id");
Log.i("huilurry","android_id="+t);
huilurry();
throw new NullPointerException("is null");
}
HandlerThread localHandlerThread;
Handler handler;
private void huilurry()
{
localHandlerThread=new HandlerThread("huilurry");
localHandlerThread.start();
handler=new Handler(localHandlerThread.getLooper());
Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
}
}
複製代碼
主要是利用了Hander和HandlerThread。
源代碼見:
http://wangjun-memory.googlecode.com/svn/trunk/android.huilurry
作者:
張祚瑋
時間:
2011-6-15 03:30
good 非常子夕棒!!!
歡迎光臨 Android 台灣中文網 (https://apk.tw/)
Powered by Discuz! X3.1