2017-03-04 121 views
1

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

但是,命名是,errm,有点混乱,我迷路了。为了启动一个服务,我创建的意图:

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

于是,我就从这个意图提取服务的名称,并用它来比较 - 但Class属性返回类的意图本身的名字,Type属性为空。

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

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

回答

3

typeof将会给C#类型/名称,你想自动生成JavaAndroid的可调用包装类,C#类型的,所以你可以得到它的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!!!"); 
} 

可以避开基于MD5汽车Java类的命名是Xamarin.Android确实经由在基于ACW-class属性的Name参数硬编码的名称:

[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

+0

非常感谢!还有关于服务属性的信息。 – greenoldman

相关问题