将数据传递给服务的onDestroy()

Kar*_*nan 6 service android android-intent

我想知道服务是否从特定活动中终止,所以我在调用时从该活动传递一个字符串stopServivce(service).

这是代码:

Intent service = new Intent(Activity.this,
                        service.class);
                service.putExtra("terminate", "activity terminated service");
                stopService(service);
Run Code Online (Sandbox Code Playgroud)

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

[编辑]

我找到了绕过这个障碍的方法,但我仍然希望我的问题得到解答.我只是onDestroy()在活动中的方法中做了我必须做的事情然后调用stopService(service).我很幸运,我的情况不需要更复杂的事情.

iag*_*een 12

没有办法访问Intentin onDestroy.您必须以其他方式发出信号(Binder,共享首选项,本地广播,全局数据或Messenger).这个答案给出了一个使用广播的好例子.您也可以通过调用startService而不是来调用它stopService.startService只有在尚未存在的情况下才启动新服务,因此多次调用startServiceIntent将服务发送给服务的机制.你看到这个技巧被使用了BroadcastReceivers.由于您可以访问Intentin onStartCommand,因此您可以通过检查Intent额外内容并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;
    }
Run Code Online (Sandbox Code Playgroud)