-1

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!

Hiperfly
  • 227
  • 1
  • 10

2 Answers2

1

Try unbindService() in your onStop().

Farouk Touzi
  • 3,451
  • 2
  • 19
  • 25
  • Using 'serv' as the argument or using no argument: "The method unbindService(ServiceConnection) in the type ContextWrapper is not applicable for the arguments (Intent)". – Hiperfly Oct 20 '14 at 08:18
  • Look at this example please : http://stackoverflow.com/questions/8341667/bind-unbind-service-example-android – Farouk Touzi Oct 20 '14 at 08:28
1

I finally solved it this way

public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.closeApp) {
        stopService(new Intent(Main.this, Bground.class));
        finish();
    }

Just adding stopService(new Intent(Main.this, Bground.class));

Thanks to this post: How to call stopservice() method of Service class from the calling activity class

Community
  • 1
  • 1
Hiperfly
  • 227
  • 1
  • 10