android看不見main函數怎麼辦?程式異常了,可以不提示“xxx軟體停止運行”嗎?

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.