Android Service (“startService & stopService”) and Play/Stop Button in One

不问归期 提交于 2019-12-06 03:52:35

You just need to declare a flag variable and declare body of onclick() based on flag value like this.

public class ServiceActivity extends Activity {
    Button play;
    int button_status=1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        play=(Button)findViewById(R.id.button1);

        play.setOnClickListener(new OnClickListener() {         
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if(button_status == 1)//play the service
                {
                button_status=0;
                Intent i=new Intent(ServiceActivity.this,Playing.class);
                startService(i);
                }
                else//stop the service
                {
                button_status=1;
                Intent i=new Intent(ServiceActivity.this,Playing.class);
                stopService(i); 
                } 
        });

    }  
}

or you can use ToggleButton for your purose.

boolean isStop = false;

public void startorStop() {
    if(isStop) {
      // play  it
    } else {
      //stop it  
    }
isStop = !isStop;
}

Just use a boolean to remember if it's on or off and toggle it

boolean isOn = false;

public void startStopButton() {
    if(isOn) {
        stopActivity();
        isOn = false;
    } else {
        startActivity();
        isOn = true;
    }
}

Now whenever your button is pressed, you can call this method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!