標籤:
今天遇到了這個問題,分享一下解決方式。
android沒有main 函數,自然也就不存在main裡面加入異常處理來實現全域異常捕獲的方案。那android程式有全域異常補貨的解決方式嗎?
答案是有的:
那就是你得繼承androidproject裡面的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
android看不見main函數怎麼辦?程式異常了,能夠不提示“xxx軟體停止執行”嗎?