stopService(intent_with_extras)-如何从服务中读取这些额外内容以停止? [英] stopService(intent_with_extras) - how do you read those extras from within the service to stop?

查看:202
本文介绍了stopService(intent_with_extras)-如何从服务中读取这些额外内容以停止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项可以通过多种方式停止的服务.每当我调用stopService(Intent)时,我都会传递一个带有一些额外功能的意图.您如何检索这些额外费用?

I have a Service that can be stopped in multiple ways. Whenever I call stopService(Intent), I pass an intent with some extras. How do you retrieve those extras?

谢谢.

推荐答案

您需要在Service中覆盖onStartCommand(),这是从startService获取对传入意图的引用的方法.

You need to override onStartCommand() in your Service this is how you get a reference to the incoming intent from startService.

在这种情况下,您将有一个特殊的动作来告诉服务停止运行.您为此目的添加了其他内容,可以在onStartCommand()方法中读取.

In this case you would have a special action in your intent to tell the service to stop itself. You add extras to this intend which can be read in the onStartCommand() method.

示例代码

public class MyService extends Service {
    @Override
    public int onStartCommand(final Intent intent, final int flags, final int startId) {
         final String yourExtra = intent.getStringExtra(YOUR_EXTRA_ID);
         // now you can e.g. call the stopSelf() method but have the extra information
    }
}

说明

每次调用context.startService(Intent) onStartCommand()都会被调用.如果该服务已经在运行,则不会创建新服务,但仍会调用onStartCommand.这样,您便可以通过运行服务的附加功能获得新的意图.

Every time you call context.startService(Intent) onStartCommand() will be called. If the service is already running a new service isn't created but onStartCommand is still called. This is how you can get a new intent with extras to a running service.

这篇关于stopService(intent_with_extras)-如何从服务中读取这些额外内容以停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆