检测服务崩溃

Pit*_*tel 5 android android-service

我有一项服务,与onStartCommand()此类似:

private User user;

@Override
public int onStartCommand(@Nullable final Intent intent, final int flags, final int startId) {
    if (user == null) {
        user = UserList.getInstance().getSpecialUser();
    }
    Assert.assertNotNull(user);

    //
    // Build notification here, seomehow based on user object
    //
    startForeground(42, notification);

    return START_STICKY;
}
Run Code Online (Sandbox Code Playgroud)

显然,我希望我的服务在前台运行,并尽可能长时间运行.

这很有效,直到我的应用程序崩溃到其网络类的深处.当发生时,是否显示应用程序崩溃对话框,用户确认它,重新创建整个应用程序,还重新创建服务,但UserList现在是空的,所以再次getSpecialUser()返回nullAssert重新启动应用程序.Android在主屏幕中放弃和用户结束.

有没有办法检测崩溃,这将使我能够更优雅地处理这种情况?

小智 4

在您的应用程序中创建一个 uncaughtExceptionHandler

public class MyApplication extends android.app.Application{

    @Override
    public void onCreate() {
        super.onCreate();

        Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

            @Override
            public void uncaughtException(Thread arg0, Throwable arg1) {
                doSomething();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)