检测服务崩溃
Detect service crash
我有一个服务,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;
}
显然,我希望我的服务在前台 运行,并且 运行 尽可能长。
这很好用,直到我的应用程序在其网络深处的某个地方崩溃 类。什么时候发生,应用程序崩溃对话框是否显示,用户确认,整个应用程序被重新创建,服务也被重新创建,但是 UserList
现在是空的,所以 getSpecialUser()
returns null
和 Assert
再次使应用程序崩溃。 Android 放弃,用户在主屏幕结束。
有没有办法检测崩溃,让我能够更优雅地处理这种情况?
在您的应用程序中创建一个未捕获的异常处理程序
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();
}
});
}
}
我有一个服务,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;
}
显然,我希望我的服务在前台 运行,并且 运行 尽可能长。
这很好用,直到我的应用程序在其网络深处的某个地方崩溃 类。什么时候发生,应用程序崩溃对话框是否显示,用户确认,整个应用程序被重新创建,服务也被重新创建,但是 UserList
现在是空的,所以 getSpecialUser()
returns null
和 Assert
再次使应用程序崩溃。 Android 放弃,用户在主屏幕结束。
有没有办法检测崩溃,让我能够更优雅地处理这种情况?
在您的应用程序中创建一个未捕获的异常处理程序
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();
}
});
}
}