0

I have button Play/Stop , One button which changes his resource by the playing or not,But when I go to other fragment(Activity) and return to fragment with Play/Stop button, music is playing but resource is default.

If i press button , it stopService and that is OK,only problem is ImageResource change.

My code :

int button_status = 1;
.... other code ...

public void onClick(View v) {
if (button_status == 1){

    button_status = 0;
    buttonPlayStop.setImageResource(R.drawable.pause);

    getActivity().startService(new Intent(getActivity(), Service.class));       

    }else{

    button_status = 1;
    buttonPlayStop.setImageResource(R.drawable.play);

    getActivity().stopService(new Intent(getActivity(), Service.class));

    }
}

Any ideas ?

user2528081
  • 63
  • 1
  • 5

1 Answers1

0

You can check the status of your Service in Activity's onResume. Depending on status of Service (running or not) you can set your button's resource.

The easiest way to keep track of Service status - is introduce some static field which will represent status

Slightly better way for checking if your activity is running or not is using following snippet (stolen from here):

private boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (MyService.class.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}
Community
  • 1
  • 1
Pavel Dudka
  • 20,754
  • 7
  • 70
  • 83