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

守給你的承諾、 提交于 2019-12-07 15:27:12

问题


I am developing an Android app and I need to make one button which will be a Play/Stop button for Android Service playing and stopping.

  • Play button is for startActivity();

  • Stop button is for stopActivity();

How do I make this?


回答1:


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.




回答2:


boolean isStop = false;

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



回答3:


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.



来源:https://stackoverflow.com/questions/17343661/android-service-startservice-stopservice-and-play-stop-button-in-one

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