I have come across an issue with my application, I have an "option" class which has a ToggleButton in it which handles the playback of music (on or off) which I created in a Session. However, if I turn the music off, change screen and go back to the option class, the ToggleButton goes back to "on", even though the music is no longer playing, which means I have to press the button twice for the music to actually come back on. Does anyone have any ideas?
Service Class:
public class MyMusicService extends Service {
MediaPlayer mp;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mp = MediaPlayer.create(this, R.raw.song);
mp.start();
mp.setLooping(true);
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(mp!=null) {
mp.stop();
mp.release();
}
mp=null;
}
}
Option class:
public class OptionsActivity extends Activity {
Intent i; // Handles MyMusicService.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
//setting the layout
i=new Intent(this, MyMusicService.class);
final ToggleButton soundOption = (ToggleButton) findViewById(R.id.soundPref);
soundOption.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on clicks to control sound being on and off.
if (soundOption.isChecked()) {
Toast.makeText(OptionsActivity.this, "Music on.", Toast.LENGTH_SHORT).show();
startService(i);
} else {
stopService(i);
Toast.makeText(OptionsActivity.this, "Music off.", Toast.LENGTH_SHORT).show();
}
}});
}
}
MainActvitiy class
Intent i;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//setting the layout
//Auto starts playing music on app launch.
i = new Intent(this,MyMusicService.class);
startService(i);
Could it be something to do with the fact in the XML I have:
android:checked="true"
Thanks for any help.