Xamarin Android C#启动服务';其他';不打电话
我有一些按钮可以启动或停止应用程序的后台服务,但由于某些原因,如果服务已经运行,我在按钮单击事件中的“其他”调用将不会被激活 这是整个按钮的代码,希望有人知道它为什么不调用:Xamarin Android C#启动服务';其他';不打电话,c#,android,if-statement,xamarin,service,C#,Android,If Statement,Xamarin,Service,我有一些按钮可以启动或停止应用程序的后台服务,但由于某些原因,如果服务已经运行,我在按钮单击事件中的“其他”调用将不会被激活 这是整个按钮的代码,希望有人知道它为什么不调用: private void StartServiceButton_Click(object sender, EventArgs e) { if (Application.Context.GetSystemService("com.prg.NotificationService") == null)
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中,im缓存意图的设置如下:
intent=newintent(Application.Context,typeof(NotificationService))代码>,此方法是获取系统服务,而不是获取自定义服务。您需要使用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;
}
private void startService按钮\u单击(对象发送方,System.EventArgs e)
{
MyService MyService=newmyservice();
如果(!isServiceRun(“MyService”))
{
Toast.MakeText(这是“服务未运行”,ToastLength.Long).Show();
Application.Context.StartService(intent);
}
其他的
{
Toast.MakeText(此“服务已在运行”,ToastLength.Long).Show();
StopService(新意图(this,typeof(MyService)));
}
}
公共布尔IServiceRun(字符串类名称)
{
bool-isRun=false;
ActivityManager ActivityManager=(ActivityManager)this.GetSystemService(Context.ActivityService);
IList,请不要忘记添加[Service]
属性。您的intent
变量指向的是什么服务?啊,忘了提一下-im缓存这个OnCreate,下面是intent设置:intent=newintent(Application.Context,typeof(NotificationService))
请编辑您的问题,将相关代码包括在内,而不是添加到注释中。阅读注释中的代码非常困难,这样人们就不必通读注释来获取有关问题的其他信息。我猜您要检查的服务的名称不是与您正在启动的服务的名称相同。我将通过获取所有正在运行的服务的列表并查看列表中的内容来调试此问题,然后启动您的服务并再次检查列表。对于某些原因的答案是,您的if
子句每次都必须返回true。Toast.MakeText(此,“服务已在运行)”,ToastLength.Long).Show();
请检查语法,尤其是“已落后”)