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.