How to prevent android app from crashing due to exception in background thread?(如何防止android应用程序由于后台线程异常而崩溃?)
问题描述
这是一个笼统的问题,从具体场景中提出来,但我想得到一个笼统的答案,如何处理以下情况:
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应用程序由于后台线程异常而崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何防止android应用程序由于后台线程异常而崩溃
基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01