0

This may be a stupid question, so please forgive me. I'm still learning java-android. So for learning purposes I've created useless program. 1. When activity is launched it starts a simple service 2. Service registers broadcast receiver ( which listens for incoming SMS messages ) 3. When SMS message arrives, service should stop itself.

Here is my code: (Service class)

// This is my service class. Lifecycle methods are ommited
public void finish() {
    Log.d("APP", "finish called");
    stopSelf();

}

Following is my broadcast receiver ( in seperate file)

@Override
public void onReceive(Context context, Intent intent) {

    Log.d("APP", "SMS Received");

    new MyService().finish();
}

So, when message arrives onReceive is triggered. Then finish() is called and executed ( I see in my LOGCAT ), but service is never destroyed.

On the other hand if I make this way in my service class:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    finish();


    return START_STICKY;
}

Then service is created and right after then destroyed. Why is working this way, and not the other way also?

4

1 回答 1

1

这是因为在您的onReceive方法中,您实例化了一项服务,而不是使用现有服务。因此,您只需要引用您的令人兴奋的服务实例,然后您应该调用finish()它的方法。

于 2013-07-22T18:35:22.983 回答