0

I am learning Java and Android development. Right now I am making an app that once launched will create a service. Then I want the service to do things based on a button that I press within my app.

This is my service class.

public class ServiceClass extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);

        // Issue is here. I cannot use findViewById
        Button start_stop_button = (Button) findViewById(R.id.button2);
        start_stop_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        // stop the wifi manager
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

My thought was I could just set a listener so when I press the button the onClick() would execute. But that wouldn't work since the service is not attached to any activity to know what the id "button1" is.

So then I thought about keeping a class variable and just updating it. These seems fairly simple but then I am not sure how I would be able to keep the service checking for the status of the variable to change. I could put it in a for loop to continue checking but I feel like a better way exists.

tldr; I have an app that kicks off a service. I want my app to be able to be closed and the service still run. But I want to have a start/stop button in my app that will trigger the service.

vs123
  • 29
  • 7

1 Answers1

0

You don't need a button as such to explicitly stop a service because it will be stopped automatically when the job inside onStartCommand is done

If you want manual control for the service inside your Activity where your button actually is then you can use stopService and startService methods

You can find a detailed explanation here

Also Service is meant to be Ui-less, so you can't do something related to the UI in the service, that's not what it is meant for. You can pop a notification and on tap you can start your activity which can give you access to the button if you're wishing to do something like that

gtxtreme
  • 1,830
  • 1
  • 13
  • 25