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?
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.
来源:https://stackoverflow.com/questions/17343661/android-service-startservice-stopservice-and-play-stop-button-in-one