External service can not be resolved by intent fil

2019-09-09 13:45发布

问题:

I am missing something essential or...

I have two applications, one of them containing exported service with intent filter declared in AndroidManifest:

<service
    android:name=".MyService"
    android:exported="true"
    android:permission="my.permission" >
    <intent-filter>
        <action android:name="my.service" />
    </intent-filter>
</service>

I can successfully bind to that service from another application by using "my.service" action. But I want to start service (send command to it). If I write:

Intent intent = new Intent("my.service");
intent.setAction("my.command");
ComponentName cn = startService(intent);

I get null in cn (service can not be resolved). But if I change this to:

PackageManager packageManager = getPackageManager();
Intent serviceIntent = new Intent("my.service");
List<ResolveInfo> services = packageManager.queryIntentServices(serviceIntent, 0);
if (services.size() > 0) {
    ResolveInfo service = services.get(0);
    intent = new Intent();
    intent.setClassName(service.serviceInfo.packageName, service.serviceInfo.name);
    intent.setAction("my.command");
    ComponentName cn = startService(intent);
}

Service is successfully started. I've seen many advices on StackOverflow containing first variant, but I can not make it work. Any ideas?

回答1:

In your code that isn't working, you are first setting your action in the constructor to "my.service". This would work, however in the next line, you are setting your action to "my.command". If you need to send a different action to the same service you will have to also add that action to your intent-filter in your manifest:

<service
    android:name=".MyService"
    android:exported="true"
    android:permission="my.permission" >
    <intent-filter>
        <action android:name="my.service" />
        <action android:name="my.command" />
    </intent-filter>
</service>


回答2:

the documentation say:

If the service is being started or is already running, the ComponentName of the actual service that was started is returned; else if the service does not exist null is returned.

i realise a simple tutorial to use "binding" whith service (in french): http://julien-dumortier.fr/service-et-binding-sous-android/ maybe it will help



回答3:

Try the following in your activity oncreate()

 intent = new Intent(this, BackHelper.class);

 startService(intent);

In manifest try

 service android:name=".BackHelper" 


回答4:

In your manifest add the following

<service 
....
android:name="the package name of your service that you imported from another project">
....
</service>

In your Activity,

//start service on create
ComponentName cn = startService(new Intent(this,service_file_you_imported.class));

//Binding the activity to the service 
doBindService();