服务意向过滤器内部的Manifest.xml目的目的、过滤器、意向、Manifest

2023-09-05 10:41:47 作者:Nice Day 好天气

这是Android开发者:组件(服务)公布其功能的 - 种意图,他们可以回应 - 通过意图过滤器

from android developers : "Components(service) advertise their capabilities — the kinds of intents they can respond to — through intent filters.

我只是无法理解里面在manifest.xml服务意图过滤器的目的,什么是能力吗?

I just cant understand the purpose of intent filter inside service in the Manifest.xml, what is the capability here?

<service
    android:name="com.x.y"
    android:enabled="true"
    android:exported="true" >
    <intent-filter>
        <action android:name="com.x.y" />
    </intent-filter>
</service>

和什么是他区别,如果我删除的意图过滤器?

and what's he difference if i remove the intent-filter?

 <service
       android:name="com.x.y"
 </service>

感谢。

推荐答案

如果你想用一个服务来执行不同的操作,然后在声明意图过滤器将有助于对要执行不同的操作你的服务相匹配。

If you want to use a service to perform different actions, then declaring an intent filter will help your service match against different actions you want to perform.

这个例子会更好地解释。 假设你有以下声明,清单文件:

The example will explain better. Suppose you have following declaration in manifest file:

<service
    android:name="MyService" >
    <intent-filter>
        <action android:name="com.x.y.DOWNLOAD_DATA" />
        <action android:name="com.x.y.UPLOAD_DATA" />
    </intent-filter>
</service>

然后在你的 IntentService 你可以过滤对这样的处理如下:

Then in your IntentService you could filter for these actions like this:

public class MyService extends IntentService {

    public MyService() {
        super("MyService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if(intent.getAction().equals("com.x.y.DOWNLOAD_DATA"){
            //download data here
        }else if(intent.getAction().equals("com.x.y.UPLOAD_DATA"){
            // upload data here
        }
    }
}

基本上,它可以让你使用,而不是例如创建两个单独的服务相同的服务,为不同的操作。

Basically, it allows you to use the same service for different actions, instead of creating two separate services for example.

然而,具有用于服务声明意图过滤器是不被视为一个很好的做法,而这正是文档说的话:

However, having intent filters declared for a service is not regarded as a good practice, and this is what the docs had to say:

注意:为确保您的应用程序是安全的,总是用一个明确的意图   启动服务,不声明意图过滤器,当你的   服务。使用一个隐含的意图启动服务是一个安全   危险,因为你不能确定什么样的服务会为回应   意图,而用户不能看到启动哪个服务

Caution: To ensure your app is secure, always use an explicit intent when starting a Service and do not declare intent filters for your services. Using an implicit intent to start a service is a security hazard because you cannot be certain what service will respond to the intent, and the user cannot see which service starts.