我想知道服务是否因特定 Activity 而终止,因此我在调用 stopServivce(service)
时传递了该 Activity 的字符串。
代码如下:
Intent service = new Intent(Activity.this,
service.class);
service.putExtra("terminate", "activity terminated service");
stopService(service);
但我似乎可以在 onDestroy()
方法中使用 getIntent().getExtras().getString("terminate);
访问此变量。
[编辑]
我找到了绕过这个障碍的方法,但我希望我的问题仍能得到解答。我只是在 Activity 的 onDestroy()
方法中做了我必须做的任何事情,然后调用了 stopService(service)
。我很幸运,我的情况不需要更复杂的东西。
最佳答案
无法访问 onDestroy
中的 Intent
。您必须以其他方式(Binder、Shared Preferences、Local Broadcast、global data 或 Messenger)向服务发送信号。 this answer 中给出了使用广播的一个很好的例子。 .您还可以通过调用 startService
而不是 stopService
来使其工作。 startService
仅在服务尚不存在时启动新服务,因此多次调用 startService
是向服务发送 Intent
的机制。您会看到 BroadcastReceivers
使用了这个技巧。由于您可以访问 onStartCommand
中的 Intent
,因此您可以通过检查 Intent
extras 并调用 stopSelf
来实现终止> 如果指示终止。这是它的草图——
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;
}
关于android - 将数据传递给 Service 的 onDestroy(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14352273/