Xamarin Android C#启动服务'else'未调用

问题描述 投票:-1回答:1

我有按钮,可以启动或停止应用程序的后台服务,但由于某些原因,如果服务已经运行,则按钮的单击事件中的“其他”调用不会被激活。

继承了整个按钮代码,希望有人知道它为什么不调用:

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

c# android if-statement xamarin service
1个回答
0
投票

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]属性。

© www.soinside.com 2019 - 2024. All rights reserved.