Retrieving the component name of a service defined in another Xamarin application

本秂侑毒 提交于 2019-12-25 09:05:09

问题


I'm currently implementing an Android Service which is to be consumed by another application of a partner company. They implement the frontend GUI, we do the business logic inside the Service.

The Service is declared like this:

[Service]
[IntentFilter(new[] { "PsiServiceHost" })]
public class PsiServiceHost : Service
{
...
}

The consuming application (optionally) starts the service and connects to it using this Intent:

serviceIntent = new Intent("PsiServiceHost");

Starting the service using ...

ApplicationContext.StartService(serviceIntent);

... results in the following log output:

08-16 10:38:17.182 3429 3429 W ContextImpl: Implicit intents with startService are not safe: Intent { act=PsiServiceHost } android.content.ContextWrapper.startService:581 md5db25c5914f35662b07cd28205cc94074.MainActivity.n_onCreate:-2 md5db25c5914f35662b07cd28205cc94074.MainActivity.onCreate:29

According to this answer on SO, starting Services using implicit intents is no longer possible even though it works fine in my case on Android 6.0 running on the Emulator.

Anyway, just to be safe I would like to use the recommended approach of constructing my Intent using a ComponentName. This would be no problem for code residing in the same project as the service as I could do this and be done with it:

Java.Lang.Class.FromType(typeof(PsiServiceHost)).CanonicalName

But unless the result from the above line of can be considered to be stable and safe to be included as string in another App, I don't know how provide the consuming App with the component Name of our Service.


回答1:


The Application with the Service:

Package Name = com.sushihangover.androidservice

[Service(Name="com.sushihangover.androidservice.MyMostAmazingService", Exported = true)]
[IntentFilter(new String[] { "myservice" }, Categories = new[] { Intent.CategoryDefault })]
public class PsiServiceHost : Service
{
    public override IBinder OnBind(Intent intent)
    {
        return null;
    }
    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        Log.Debug("SO", "MyMostAmazingService Has Been Started");
        return base.OnStartCommand(intent, flags, startId);
    }
}

The other application starting MyMostAmazingService:

var intent = new Intent();
// Package name first, Service Class Name Second
intent.SetClassName("com.sushihangover.androidservice", "com.sushihangover.androidservice.MyMostAmazingService");
StartService(intent);


来源:https://stackoverflow.com/questions/38971274/retrieving-the-component-name-of-a-service-defined-in-another-xamarin-applicatio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!