我想知道服务是否已从特定 Activity 终止,因此我在调用stopServivce(service)时从该 Activity 传递了一个字符串。

这是代码:

Intent service = new Intent(Activity.this,
                        service.class);
                service.putExtra("terminate", "activity terminated service");
                stopService(service);

但是我似乎可以在getIntent().getExtras().getString("terminate);方法中使用onDestroy()访问此变量。

[编辑]

我找到了解决这个障碍的方法,但是我希望我的问题仍然可以得到解答。我只是在 Activity 中的onDestroy()方法中做了所有要做的事情,然后称为stopService(service)。我很幸运,我的情况不需要任何更复杂的事情。

最佳答案

无法访问Intent中的onDestroy。您必须以其他方式(活页夹,共享首选项,本地广播,全局数据或Messenger)向服务发出信号。 this answer中给出了一个使用广播的很好的例子。您还可以通过调用startService而不是stopService来使其工作。 startService仅在尚不存在新服务的情况下启动一项新服务,因此多次调用startService是将Intent s发送至该服务的机制。您会看到BroadcastReceivers使用了这个技巧。由于您可以访问Intent中的onStartCommand,因此可以通过检查Intent Extras并在指示终止时调用stopSelf来实现终止。这是实际操作的示 Intent -

public int onStartCommand(Intent intent, int flags, int startId) {
        final String terminate = intent.getStringExtra("terminate");

        if(terminate != null) {
            // ... do shutdown stuff
            stopSelf();
        }
        return START_STICKY;
    }

09-20 19:01