Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onStop called before onStart

I have a activity which is called from a AlarmManager. It is an alarm message.

When the Activity is called from the Key Guard, the lifecycle goes from onCreate -> onStart -> onResume -> onPause -> onStop and then goes back to onCreate -> onStart -> onResume.

Since it's a alarm activity, I have put the MediaPlayer.stop line inside the Activity's onStop, but now the alarm sound stops just after it starts.

If I put the MediaPlayer.stop inside onDestroy, I get the correct behavior, but if the user press the home button, the activity goes away and the sound keeps playing.

Anyone can tell why onPause and onStop are called during in this situation?

EDIT: After some investigation in the log, I found this line:

11-26 17:39:01.273: I/ActivityManager(385): Activity reported stop, but no longer stopping: ActivityRecord{41827a90 u0 net.xisberto.workschedule/.AlarmMessageActivity}
like image 805
Xisberto Avatar asked Nov 26 '12 19:11

Xisberto


1 Answers

OK, after more than a year I realized that this question never got an answer, although I got to handle the problem, so here it goes:

Now I'm starting the MediaPlayer during onResume, but i don't start it again if it's already playing:

@Override
protected void onResume() {
    super.onResume();
    ...
    if (!mMediaPlayer.isPlaying()) {
        mMediaPlayer.start();
    }
    ...
}

And I stop it during onStop, but only if the Activity isFinishing:

@Override
protected void onStop() {
    super.onStop();
    if (isFinishing()) {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    } else {
        ...
    }
}

Since during the described situation the Activity isn't finishing, but restarting (configuration change, I think), the MediaPlayer don't stop.

My code isn't exactly like that because I use some other functions and I use a Notification to bring the user back to the Activity. The complete code is here: https://github.com/xisberto/workschedule/blob/master/src/net/xisberto/work_schedule/AlarmMessageActivity.java

like image 179
Xisberto Avatar answered Sep 28 '22 05:09

Xisberto