如何找到我自己的服务?

时间:2017-03-04 20:13:44

标签: android xamarin xamarin.android android-service

我想在活动中找到自己的服务(RadarService) - 检查服务是否正在运行。

然而,命名是错误的,有点令人困惑,我迷失了。为了启动服务,我创建了意图:

 this.radarIntent = new Intent(this, typeof(RadarService));

因此,我尝试从此intent中提取服务的名称并将其用于比较 - 但Class属性返回intent本身的类的名称,Type属性为空。

好的,所以我尝试使用typeof(RadarService).ToString() - 这给了我字符串MyNamespace.RadarService,很好。但是,当我尝试将其与我失败的正在运行的服务列表进行匹配时,因为我的服务列为md5--here-comes-md5-hash--.RadarService(在ClassName中设置为ShortClassNameActivityManager.RunningServiceInfo

那么如何找到我自己的服务?

1 个答案:

答案 0 :(得分:3)

typeof将提供C#类型/名称,您需要C#类型的自动生成的Java Android Callable Wrapper 类,以便您可以获得CanonicalName

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

示例:

var intent = new Intent(this, typeof(StackOverFlowService));
StartService(intent);

var serviceName = Java.Lang.Class.FromType(typeof(StackOverFlowService)).CanonicalName;
var manager = (ActivityManager)GetSystemService(ActivityService);
foreach (var item in manager.GetRunningServices(int.MaxValue))
{
    if (item.Service.ClassName == serviceName)
        Log.Debug("SO", "Service is running!!!");
}

您可以通过基于ACW的类属性上的Xamarin.Android参数对名称进行硬编码来避免Name所做的基于MD5的自动Java类命名:

[Service(Label = "StackOverFlowService", Name="com.sushihangover.WickedApp.StackOverFlowService")]
[IntentFilter(new String[] { "com.sushihangover.StackOverFlowService" })]
public class StackOverFlowService : Service
{
~~~
}

现在,您的服务Java类名称将是com.sushihangover.WickedApp.StackOverFlowService而不是md58b0fd40f68fa0d8c16b76771789ed62a.StackOverFlowService

相关问题