1

I'm creating a music player application.

When the music plays I'm displaying a notification of current song (similar to default Android music player app).

I'm running music in a Service and handling notification show/hide within that service only.

When the application gets destroyed abruptly/crashes, the music service is stopped & so is the music in the background (which is a correct behavior, i guess).

But even after crash, the notification still remains.

How can I handle this issue?

One scenario handled:

Music Service is running and notification is displayed.

User clicks on recent apps and kills my application, so service stops , but notification still visible.

How I handled it:

It is expected that if music is playing and user finishes the MainActivity, then music should keep playing in the background.

So , if backpressed == true, then in onDestroy(), do not cancel the notification. (Activity finished by user)

Else, if backpressed == false, then in onDestroy(), the notification. (Activity killed abruptly)

@Override
public void onBackPressed() {
    super.onBackPressed();
    mBackPressed = true;
}

@Override
protected void onDestroy() {
    if (!mBackPressed) {
        mMusicService.hideStatusBarNotification();
    }

    super.onDestroy();
    Log.e(TAG, "onDestroy() called - Activity");
}

Is this handling a good approach.

Also, this is just one scenario, I cant think of how application+service can be killed abruptly, & how to handle it?

Thank You

reiley
  • 3,759
  • 12
  • 58
  • 114
  • 1
    related : http://stackoverflow.com/questions/12997800/cancel-notification-on-remove-application-from-multitask-panel – ben75 Jul 03 '14 at 15:25

1 Answers1

0

The way you handle it seems pretty good to me. An alternative could be to add an Application class, that catch any Exception that is uncatched by your own code. This way you are sure that the code contained in this class is executed before any crash. The class may look like this:

public class MyApplication extends Application {
// uncaught exception handler variable
private Thread.UncaughtExceptionHandler defaultUEH;

// handler listener
private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler =
        new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable ex) {

                Log.e("UNCAUGHT EXCEPTION CAUGHT!", ex.toString());

                // Hide notification here ;)

                // re-throw critical exception further to the os (important)
                defaultUEH.uncaughtException(thread, ex);
            }
        };

public MyApplication() {
    defaultUEH = Thread.getDefaultUncaughtExceptionHandler();

    // setup handler for uncaught exception
    Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
}

}

After, you instantiate this class at every app start, in the onCreate() method of your activity.

Marino
  • 800
  • 1
  • 12
  • 26