Reputation: 115
I have a mediaplayer in my settings activity which plays a song when the toggle button is turned on. It works fine and when the activity is changed, the music continues to play which is what I want. The problem is, when I go back to the settings activity again, the toggle button is set to off and once clicked it starts a new media player which plays alongside the current one. Is there anyway for it to remember that the original media player is turned on?
public class Settings extends AppCompatActivity {
public MediaPlayer mp = null;
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
initControls();
Button b = (Button) findViewById(R.id.toggleButton);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Spinner spinner = (Spinner) findViewById(R.id.spinner);
String text = spinner.getSelectedItem().toString();
if (mp == null) {
int song = getResources().getIdentifier(text, "raw", "com.example.dan14.memorygame");
mp = MediaPlayer.create(Settings.this, song);
mp.start();
} else {
mp.stop();
mp = null;
}
}
});
}
Upvotes: 0
Views: 60
Reputation: 108
In my idea your code should work fine at least most of the time.
Try
public static MediaPlayer mp = null;
Update: Normally when inter-activity property is needed such as music playing, you should try Service, one important Android feature. At least you should get know of it and decide what to do. Here's a comprehensive tutorial from Google. http://developer.android.com/guide/topics/media/mediaplayer.html
Upvotes: 1
Reputation: 48258
Move the Button out of the onCreate
and place it as an Activity Member.
Upvotes: 0