检索在另一个Xamarin应用程序中定义的服务的组件名称
本文关键字:服务 组件 定义 另一个 Xamarin 应用程序 检索 | 更新日期: 2023-09-27 18:02:30
我目前正在实现一个Android服务,该服务将由合作伙伴公司的另一个应用程序使用。他们实现前端GUI,我们在服务内部做业务逻辑。
服务是这样声明的:
[Service]
[IntentFilter(new[] { "PsiServiceHost" })]
public class PsiServiceHost : Service
{
...
}
消费应用程序(可选)启动该服务并使用此Intent连接到它:
serviceIntent = new Intent("PsiServiceHost");
使用…启动服务
ApplicationContext.StartService(serviceIntent);
…输出如下日志:
08-16 10:38:17.182 3429 3429 W ContextImpl: Implicit intents withstartService不安全:Intent {act=PsiServiceHost}android.content.ContextWrapper.startService: 581md5db25c5914f35662b07cd28205cc94074.MainActivity.n_onCreate: 2md5db25c5914f35662b07cd28205cc94074.MainActivity.onCreate: 29日
根据SO的答案,使用隐式意图启动服务不再可能,即使它在我的情况下在模拟器上运行的Android 6.0上运行良好。
无论如何,为了安全起见,我想使用使用ComponentName构造我的Intent的推荐方法。对于与服务位于同一项目中的代码来说,这没有问题,因为我可以这样做并使用它:
Java.Lang.Class.FromType(typeof(PsiServiceHost)).CanonicalName
但是,除非上面一行的结果可以被认为是稳定和安全的,可以作为字符串包含在另一个应用程序中,否则我不知道如何为消费应用程序提供我们服务的组件名称
应用程序与服务:
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);
}
}
启动MyMostAmazingService
的其他应用程序:
var intent = new Intent();
// Package name first, Service Class Name Second
intent.SetClassName("com.sushihangover.androidservice", "com.sushihangover.androidservice.MyMostAmazingService");
StartService(intent);