从Xamarin表单启动android服务

Edw*_*lne 4 c# android xamarin.forms

在Visual Studio中,我创建了一个新的类库(Xamarin Forms):

Xamarin类库

在这里,我添加了我的服务,并为启动的服务提供了最基本的实现(注意-不是绑定的服务。期望-在启动/停止应用程序时显示敬酒:-

namespace AndroidBatteryService
{
    public class AndroidBatteryService : Service
    {

        public AndroidBatteryService()
        {

        }

        [return: GeneratedEnum]
        public override StartCommandResult OnStartCommand(Intent intent,    [GeneratedEnum] StartCommandFlags flags, int startId)
        {
            Toast.MakeText(this, "The Battery Service was just started",  ToastLength.Long).Show();
            return base.OnStartCommand(intent, flags, startId);
        }

        public override void OnCreate()
        {
            base.OnCreate();
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
            Toast.MakeText(this, "The Battery Service has been stopped",     ToastLength.Long).Show();
        }

        public override IBinder OnBind(Intent intent)
        {
            //started service, NOT a binded service - return null...
            return null;
        }
   }
}
Run Code Online (Sandbox Code Playgroud)

在另一个项目中,我正在运行以下代码来调用此服务:

public void StartBatteryService()
{
    Intent intent = new Intent(Android.App.Application.Context, typeof(AndroidBatteryService.AndroidBatteryService));
    Android.App.Application.Context.StartService(intent);
}
Run Code Online (Sandbox Code Playgroud)

代码运行了(我可以执行它),但是实际服务中的OnStartCommand方法没有运行,我希望它可以运行。有任何想法吗??

Jas*_*onB 5

我认为问题在于您需要使用以下方法装饰服务类:

[Service (Label = "AndroidBatteryService", Icon = "@drawable/Icon") ]
Run Code Online (Sandbox Code Playgroud)

这导致Xamarin在构建过程中将以下内容放入生成的AndroidManifest.xml文件中(您可以在\ obj \ Debug \ android目录中找到此文件)

<service android:icon="@drawable/icon" android:label="AndroidBatteryService" android:name="md55...1a.AndroidBatteryService" />
Run Code Online (Sandbox Code Playgroud)

我在应用程序中使用了非常相似的代码,并且运行良好。(尽管您现在可能已经解决了这个问题。)