简体   繁体   English

如何在android上制作服务的监听器

[英]How to make a listener of a service on android

I have this code to check if a service is active, but I would like to know if there is any way for an EditText to show the status of the service, without making this query per second, or in a separate thread, or linking it in some way?我有这个代码来检查服务是否处于活动状态,但我想知道是否有任何方法可以让 EditText 显示服务的状态,而无需每秒进行此查询,或在单独的线程中,或链接它某种程度上来说? that it is possible to detect if the service stopped可以检测服务是否停止

private bool MiServicioEstaCorriendo(Class @class, Context contexto)
        {
            ActivityManager manager = (ActivityManager)contexto.GetSystemService(Context.ActivityService);
            foreach (ActivityManager.RunningServiceInfo service in manager.GetRunningServices(Integer.MaxValue))
            {
                if (@class.Name.Equals(service.Service.ClassName))
                {
                    Log.Info(typeof(BroadcastGps).Name, "MiServcicioEstaCorriendo: true");
                    return true;
                }
            }
            Log.Info(typeof(BroadcastGps).Name, "MiServcicioEstaCorriendo: false");
            return false;
        }

You are basically in need of a way to pass events/messages among classes within your application.您基本上需要一种在应用程序中的类之间传递事件/消息的方法。 So this question probably goes down to Android & C# implementation of such a pattern.所以这个问题可能归结为这种模式的 Android & C# 实现。 Xamarin.Forms has a MessagingCenter class, but since you are using Xamarin.Native, you would have to create something yourself Xamarin.Forms 有一个MessagingCenter类,但由于您使用的是 Xamarin.Native,您必须自己创建一些东西

There's nothing actually already baked in to Android or C#, but so you can implement one of the most common ways to let a class spread an event/message using the "Listener" (term used in Android) or " Delegate " (term used in C#) technique.实际上,Android 或 C# 中没有任何东西,但是您可以实现一种最常见的方法,让类使用“侦听器”(Android 中使用的术语)或“ 委托”(Android 中使用的术语)来传播事件/消息C#) 技术。

There are frameworks too like PubNub that you can use as Nuget packages that simplify everything for you.也有像PubNub这样的框架,您可以将它们用作 Nuget 包,为您简化一切。

Some more resources to understand the concept: Wikipedia , IBM .了解这个概念的更多资源: WikipediaIBM And Some Android resources: Handlers , AsyncTasks , Parcelables .以及一些 Android 资源: HandlersAsyncTasksParcelables

Don't forget that your event to update your EditText may not be fired on the Main UIThread so you won't be able to see the changes unless you force that update line to be Run on UI Thread.不要忘记更新 EditText 的事件可能不会在 Main UIThread 上触发,因此除非您强制该更新行在 UI Thread 上运行,否则您将无法看到更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM