如何防止android应用程序由于后台线程异常而崩溃?

时间:2023-03-03
本文介绍了如何防止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应用程序由于后台线程异常而崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:Eclipse 工作区在启动时崩溃 下一篇:Android 致命信号 11

相关文章