I am trying to make an app that has only one activity and when you press a button the app is closed but a service remains in the background. However, I want to have an option button (in onCreateOptionsMenu) called 'Close App' so when you click it the Activity is finish();
and the service is killed. The problem is that I know how to close the Activity, but not how to kill the service from the Activity. Here is part of my code (I omited couple basic methods for simplicity):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bDone.setOnClickListener(this);
}
public void Onclick(){
Intent serv = new Intent(Main.this, Bground.class);
startService(serv);
finish();
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.closeApp) {
finish();
}
return super.onOptionsItemSelected(item);
}
I have tried putting the Intent serv;
as a global variable and writing stopService(serv);
right above the finish();
in the onOptionsItemSeected but it gives me an error.
Thanks!