0

I have one button for play and stop. The buttons work perfectly, but when I play music, go into the background to some other app, then return to my app, my play/stop button is starting to play again if I press it. This is a problem because I need to press the play button again (although the music is playing) and then press the stop button. I find way to do it with onSaveInstanceState() , but it is not working , problem is here again I need to press play button to stop music whitch is playing in background my code:

int button_status=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.player);
    if (savedInstanceState != null) {
        button_status = savedInstanceState.getInt("EXTRA_IS_ON");
    }}

@Override
public void onSaveInstanceState(Bundle outState) {

    outState.putInt("EXTRA_IS_ON", button_status);
    super.onSaveInstanceState(outState);
}

public void onClick(View v) {
    internetKonekcija = pk.konekcijaPremaInternetu();


    if(button_status == 1)//play the service
    {
    button_status=0;
    startService(new Intent(this, Service.class));
    }
    else//stop the service
    {
    button_status=1;

    stopService(new Intent(this, Service.class));
    }       
user2528081
  • 63
  • 1
  • 5
  • Have you tried using a ToggleButton? I'm pretty sure it saves whether it's checked or not. – Karakuri Jul 03 '13 at 14:45
  • I agree with Karakuri toggle button would work better and less code as well. And it does track its own selection state. – yams Jul 03 '13 at 14:52

2 Answers2

0

Why you check saved state in onCreate? check it in onRestoreInstanceState. Maybe it helps.

Actually your app go to onPause when you go to background. I really don't convinced that onSavedInstanceState is fires when app moves to background.

S.Shustikov
  • 93
  • 1
  • 1
  • 4
0

I'd suggest approaching this differently: instead of trying to store a flag for whether your service is running or not and therefore having the possibility of the flag being wrong, why not query whether the service is running whenever you need to? See this answer for a suggestion of how: https://stackoverflow.com/a/5921190/441899

Community
  • 1
  • 1
Jules
  • 14,841
  • 9
  • 83
  • 130