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