简体   繁体   中英

Is onCreate() called before onStart() if onStart() is called after onRestart()?

I don't understand that when I release the MediaPlayer obj's resources using the release() method in the onStop() method when I resume the activity, why can the MediaPlayer still play the sound after I click the play button even when the obj was released in the onStop() method and I am sure that the onStop() method is called. So what might be the reason for this to happen, is the onCreate() method called as soon as the onRestart() method calls the onStart() method or is there any other reason for it?

My logic is that if in the onStop() method I release the MediaPlayer obj's resources then there should be no instance in the obj that holds the audio file in it so when the activity is resumed no audio shall be played as the obj is assigned a null value in the releaseMediaPlayerResources() method after its resources are released so which is why I think for the obj to get an instance the onCreate() must be called as that is the method in which I have assigned the MediaPlayer obj an audio file.

private MediaPlayer audio;
private Button playBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_list_view);
    playBtn = findViewById(R.id.playBtn);
        
    playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                releaseMediaPlayerResources();
                audio = MediaPlayer.create(this, R.raw.song);
                audio.start();
            }
    });

}
@Override
protected void onStop() {
    super.onStop();
    releaseMediaPlayerResources();
    Toast.makeText(this, "onStop() releasing res...", Toast.LENGTH_SHORT).show();
}

private void releaseMediaPlayerResources() {
    if(audio!=null){
        audio.release();
        audio = null;
    }
}

Refer to this image, it always helped me when I am wondering what function is called when?
Android 活动生命周期

why can the MediaPlayer still play the sound after I click the play button even when the obj was released in the onStop() method?

Because on each button click you first release the MediaPlayer and then create a new instance of it and start:

releaseMediaPlayerResources();
audio = MediaPlayer.create(YourActivity.this, R.raw.song);
audio.start();

is the onCreate() method called as soon as the onRestart() method calls the onStart() method?

No .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM