標籤:des android style class blog code
今天遇到了這個問題,分享一下解決方案。
android沒有main 函數,自然也就不存在main裡面添加異常處理來實現全域異常捕獲的方案。那android程式有全域異常補貨的解決方案嗎?
答案是有的:
那就是你得繼承android工程裡面的application,如:
public class ReaderApplication extends Application implements Thread.UncaughtExceptionHandler{......}
並實現線程異常補貨介面:Thread.UncaughtExceptionHandler
這樣你的程式,只要有沒有處理的異常,都會在下面的uncaughtException函數中被捕獲了。我的做法是重啟應用程式。
@Overridepublic void uncaughtException(Thread thread, Throwable ex) {// TODO Auto-generated method stub//System.exit(0);Intent intent = getBaseContext().getPackageManager() .getLaunchIntentForPackage(getBaseContext().getPackageName()); PendingIntent restartIntent = PendingIntent.getActivity( getApplicationContext(), 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK); //退出程式 AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒鐘後重啟應用 System.exit(0); }
但不得不說的是,你得在application的oncreate函數中加上異常回調介面的註冊:
Thread.setDefaultUncaughtExceptionHandler(this);
最後是,你得在AndroidManifest.xml中,將這句話修改為自己的Application:
<application
android:name="com.founder.reader.ReaderApplication"
好了,有了上面的全域異常處理,也就不用所謂的main函數才能實現的了。同時,程式也不會再提示“xxx軟體停止運行”了。
最後:程式重啟得用系統時鐘來重啟,否則程式都退出了,誰來執行重啟任務:
AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒鐘後重啟應用
最最後,不忘給自己的小網站打個廣告:程式員必備軟體:www.uhdesk.com