問(wèn)題描述
這是一個(gè)籠統(tǒng)的問(wèn)題,從具體場(chǎng)景中提出來(lái),但我想得到一個(gè)籠統(tǒng)的答案,如何處理以下情況:
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:
背景:
我有一個(gè)應(yīng)用程序,它使用一些 3rd 方庫(kù)(廣告網(wǎng)絡(luò)提供商 SDK - 特別是 - AdMob
SDK,基于 Google Play 服務(wù)
).這個(gè)庫(kù)的功能對(duì)應(yīng)用程序來(lái)說(shuō)并不重要.該庫(kù)創(chuàng)建一個(gè)或多個(gè)后臺(tái)工作線程.有時(shí)(非常罕見(jiàn)的情況)這些后臺(tái)線程之一中存在未處理的異常,導(dǎo)致應(yīng)用程序崩潰.我想忽略由這個(gè)庫(kù)引起的所有異常,不管它們的原因是什么:在最壞的情況下,應(yīng)用程序用戶(hù)不會(huì)看到廣告——這比應(yīng)用程序崩潰要好得多.
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.
由于庫(kù)本身創(chuàng)建了后臺(tái)線程 - 我不能只通過(guò) try/catch 包裝它們.
Since the library itself creates the background threads - I cannot just wrap them by try/catch.
問(wèn)題
有什么方法可以捕獲所有未處理的后臺(tái)(非主)線程異常并在這種情況下殺死線程并防止應(yīng)用崩潰?
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?
相關(guān)問(wèn)題
我看到了很多問(wèn)題,但其中一些問(wèn)題太具體(并沒(méi)有涵蓋我的情況),另一些問(wèn)題是指開(kāi)發(fā)人員可以控制線程創(chuàng)建并且能夠用 try/包裝整個(gè)線程的情況抓住.如果我仍然錯(cuò)過(guò)了涉及此案例的相關(guān)問(wèn)題,我將不勝感激該鏈接
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 擴(kuò)展所有活動(dòng).該應(yīng)用永遠(yuǎn)不會(huì)崩潰
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());
}
});
}
}
這篇關(guān)于如何防止android應(yīng)用程序由于后臺(tái)線程異常而崩潰?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!