我有按钮,可以启动或停止应用程序的后台服务,但由于某些原因,如果服务已经运行,则按钮的单击事件中的“其他”调用不会被激活。
继承了整个按钮代码,希望有人知道它为什么不调用:
private void StartServiceButton_Click(object sender, EventArgs e)
{
if (Application.Context.GetSystemService("com.prg.NotificationService") == null)
{
Application.Context.StartService(intent);
}
else
{
Toast.MakeText(this, "Service already running", ToastLength.Long).Show();
}
}
我在OnCreate中缓存意图,这里是设置:
intent = new Intent(Application.Context, typeof(NotificationService));
Here is about the GetSystemService
method,这种方法是让系统服务不要获得你的自定义服务。您需要使用ActivityManager
来获取设备上运行的所有服务,并找到您想要启动或停止的服务。
请使用下面的代码来实现您的目标:
private void StartServiceButton_Click(object sender, System.EventArgs e)
{
MyService myService = new MyService();
if (!isServiceRun("MyService"))
{
Toast.MakeText(this, "Service not running", ToastLength.Long).Show();
Application.Context.StartService(intent);
}
else
{
Toast.MakeText(this, "Service already running", ToastLength.Long).Show();
StopService(new Intent(this,typeof(MyService)));
}
}
public bool isServiceRun( string className)
{
bool isRun = false;
ActivityManager activityManager = (ActivityManager)this.GetSystemService(Context.ActivityService);
IList<ActivityManager.RunningServiceInfo> serviceList = activityManager.GetRunningServices(40);
int size = serviceList.Count;
for (int i = 0; i < size; i++)
{
Android.Util.Log.Error("Service Name=====", serviceList[i].Service.ClassName);
if (serviceList[i].Service.ClassName.Contains(className) == true)
{
isRun = true;
break;
}
}
return isRun;
}
Here is the usage about Service
in Xamarin.Android,请不要忘记添加[Service]
属性。