我想知道服务是否已从特定 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;
}