問題描述
這是一個籠統的問題,從具體場景中提出來,但我想得到一個籠統的答案,如何處理以下情況:
It's a general question, which raised from specific scenario, but I'd like to get a general answer how to deal with the following situation:
背景:
我有一個應用程序,它使用一些 3rd 方庫(廣告網絡提供商 SDK - 特別是 - AdMob
SDK,基于 Google Play 服務
).這個庫的功能對應用程序來說并不重要.該庫創建一個或多個后臺工作線程.有時(非常罕見的情況)這些后臺線程之一中存在未處理的異常,導致應用程序崩潰.我想忽略由這個庫引起的所有異常,不管它們的原因是什么:在最壞的情況下,應用程序用戶不會看到廣告——這比應用程序崩潰要好得多.
I have an app, which is using some 3rd party library (ad network provider SDK - specifically - AdMob
SDK, based on Google Play Services
). Functionality of this library is not critical for the application. The library creates one or more background worker threads. Sometimes (very rare case) there is an unhandled exception in one of these background threads, causing to crashing the application. I'd like to ignore all exceptions, caused by this library, regardless of their cause: in worst case the app user will not see an ad - it's much better than app crash.
由于庫本身創建了后臺線程 - 我不能只通過 try/catch 包裝它們.
Since the library itself creates the background threads - I cannot just wrap them by try/catch.
問題
有什么方法可以捕獲所有未處理的后臺(非主)線程異常并在這種情況下殺死線程并防止應用崩潰?
Is there any way to catch all non-handled background (non-main) thread exceptions and just to kill the thread in such case, and to prevent app crash?
相關問題
我看到了很多問題,但其中一些問題太具體(并沒有涵蓋我的情況),另一些問題是指開發人員可以控制線程創建并且能夠用 try/包裝整個線程的情況抓住.如果我仍然錯過了涉及此案例的相關問題,我將不勝感激該鏈接
I saw a lot of several questions, but some of them are too specific (and not covering my case), others refer to situation when the developer has a control on thread creation and is able to wrap the whole thread with try/catch. If I still missed the relevant question, covering this case, I will appreciate the link
推薦答案
您需要做的就是使用 BaseActivity 擴展所有活動.該應用永遠不會崩潰
All you need to do is Extend all the activities with BaseActivity. The app never crashes at any point
BaseActivity 的代碼片段:
Code sniplet for BaseActivity :
public class BaseActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
Log.e("Error"+Thread.currentThread().getStackTrace()[2],paramThrowable.getLocalizedMessage());
}
});
}
}
這篇關于如何防止android應用程序由于后臺線程異常而崩潰?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!