android - 如何找到我自己的服务?

标签 android xamarin xamarin.android android-service

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

但是命名有点困惑,我迷路了。为了启动服务,我创建了 Intent :

 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)。

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

最佳答案

typeof 将提供 C# 类型/名称,您需要自动生成的 Java Android Callable Wrapper 该 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!!!");
}

您可以通过基于 ACW 的类属性上的 Name 参数对名称进行硬编码,从而避免 Xamarin.Android 执行的基于 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

关于android - 如何找到我自己的服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42600863/

相关文章:

android - 了解 firebase 的 createUser 函数(特别是 android 库)

ios - 如何识别 Xamarin.iOS 中的 iOS 应用程序扩展崩溃?

Android,尝试使用 muPDF 在我的 Xamarin Android 应用程序中查看 PDF

android - 在 C# 中使用 BitmapFactory.DecodeFile 时内存占用量较大(对于小图像占用大量内存)

android - 使用glOrthof的OpenglES多平台屏幕比例解决方案

android - 在 R.Raw 中打开文件音频

xamarin - DependencyService.Get<>() 不起作用

Android.Gms.Analytics.HitBuilders.AppViewBuilder 已过时

android - 是否有可能在 Xamarin 中为 Android Button 赋值?

java - 如何从 Google Places API 中删除不需要的地点?