Search code examples
javaandroidondestroy

How to run something after stopService?


I want to receive message when Service stops, so I added some code into onDestroy section of service class.

Here is the code for Main Activity

    if(view.getId() == R.id.stopButton) {
        stopService(new Intent(this, MyService.class));
        Toast.makeText(this, "Button Pressed", Toast.LENGTH_SHORT).show();

And this is for Service

public void onDestroy() {
        Toast.makeText(this, "Some Message", Toast.LENGTH_SHORT).show();
    }

What I want to achieve is to display "Some Message" and then "Button Pressed" message when stop button is pressed.

In logical sense, "Some Message" should displayed first and then followed by "Button Pressed" message. But no matter how I try(changing the sequence of stopService) "Button Pressed" message shows up first.

Am I missing something here? please help.. :)


Solution

  • stopService() is asynchronous. When you call stopService(), you get control back immediately, and the service will be stopped later.