Android:如何获得服务收到的意图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1964969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:57:35  来源:igfitidea点击:

Android: how to get the intent received by a service?

androidserviceandroid-intent

提问by BuzBuza

I'm starting a service with an intent where I put extra information.

我正在启动一项服务,目的是在其中放置额外的信息。

How can I get the intent in the code of my service?

如何在我的服务代码中获得意图?

There isn't a function like getIntent().getExtras()in service like in activity.

没有getIntent().getExtras()像活动那样的服务功能。

回答by Alagu

onStart()is deprecated now. You should use onStartCommand(Intent, int, int)instead.

onStart()现在已弃用。你应该onStartCommand(Intent, int, int)改用。

回答by CommonsWare

Override onStart()-- you receive the Intentas a parameter.

覆盖onStart()- 您收到Intent作为参数。

回答by David Miguel

To pass the extras:

要传递额外内容:

Intent intent = new Intent(this, MyService.class);
intent.putExtra(MyService.NAME, name);
...
startService(intent);

To retrieve the extras in the service:

要检索服务中的附加内容:

public class MyService extends Service {  
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        String name = intent.getExtras().getString(NAME);
        ...
    } 
    ...
}