Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect service crash

I have a service, with onStartCommand() similiar to this:

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;
}

Obviously, I want my service to run in foreground, and run for as long as possible.

This works well, until my app crashes somewhere deep in its network classes. When happens then, is the app crash dialog is displayed, user confirms it, the whole app is recreated, also the service gets recreated, but UserList is now empty, so getSpecialUser() returns null and Assert crasehs the app, again. Android gives up and user ends in home screen.

Is there a way to detect the crash which will allow me to handle the situation more gracefully?

like image 513
Pitel Avatar asked Sep 26 '22 19:09

Pitel


1 Answers

create an uncaughtExceptionHandler in your Application

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();
            }
        });
    }
}
like image 182
rainash Avatar answered Sep 30 '22 06:09

rainash