简体   繁体   中英

resuming my application from background

i have created an application its a music player with just a simple layout one button for play and stop. when i press the play button the music start to play and the play button change to stop button.. then when i press the back button the application goes in to background so i have to go to the menu and launch the application from there the problem is if i do that android starts a new instance of my application and the stop button is back to play button .. which i dont want to.. all i want is that android resume my application and bring it back to foreground and retain the state of all my buttons.

When a user exits your app with the back button, your app is stopped and no state is saved. You'll need to save whatever state you need to resume the app in one of the lifecycle methods like Activity.onStop. There is a good description of the activity lifecycle here .

There is another section farther down called Saving Persistent State which talks a bit more about using Shared Preferences .

[edit]

I'm making some assumptions here about what your code might look like, but hopefully you can at least adapt these ideas to work with what you've got. Adding just a few things to your Activity will probably do the trick.

You'll want to be able to save the relevant settings when your app is closed:

@Override
public void onSaveInstanceState(Bundle icicle) {
    super.onSaveInstanceState(icicle);
    icicle.putString("path", mMediaPath);
    icicle.putInt("time", mMediaPlayer.getCurrentPosition());
    icicle.putBoolean("isPlaying", mMediaPlayer.isPlaying());
}

You'll want to set up a method to initialize your media player from those settings. Something like this:

private void initialize(String path, int time, boolean isPlaying) {
    mMediaPlayer.setDataSource(path);
    mMediaPlayer.seekTo(time);
    if (isPlaying) mMediaPlayer.start();
    findViewById(R.id.my_play_button).setBackgroundResource(isPlaying? R.drawable.pause_button: R.drawable.play_button);
}

Then, you can call that when your activity is recreated:

@Override
public void onRestoreInstanceState(Bundle icicle) {
    super.onRestoreInstanceState(icicle);
    String path = icicle.getString("path", DEFAULT_TRACK);
    int time = icicle.getInt("time", 0);
    boolean isPlaying = icicle.getBoolean("isPlaying", false);
    this.initialize(path, time, isPlaying);
}

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