Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

android - Purpose of Service Intent-Filter inside Manifest.xml

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

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>

thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...