[英]Starting an android Service from Xamarin forms
In Visual Studio I created a new class library (Xamarin Forms) :- 在Visual Studio中,我创建了一个新的类库(Xamarin Forms): -
Xamarin class library Xamarin类库
Here I added my service and gave it the most basic implementation possible for a started service (note - not a bound service. Expecting - toasts to be displayed when the application is started / stopped :- 在这里,我添加了我的服务,并为已启动的服务提供了最基本的实现(注意 - 不是绑定服务。期望 - 在启动/停止应用程序时显示的Toast: -
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;
}
}
}
In another project I am invoking this service my running the following code :- 在另一个项目中,我正在调用此服务,运行以下代码: -
public void StartBatteryService()
{
Intent intent = new Intent(Android.App.Application.Context, typeof(AndroidBatteryService.AndroidBatteryService));
Android.App.Application.Context.StartService(intent);
}
The code runs (I can step over it), but the OnStartCommand method in the actual service is not run and I am expecting it to. 代码运行(我可以跳过它),但实际服务中的OnStartCommand方法没有运行,我期待它。 Any ideas??
有任何想法吗??
I think the problem is that you need to decorate the service class with:- 我认为问题是你需要用以下方法装饰服务类:
[Service (Label = "AndroidBatteryService", Icon = "@drawable/Icon") ]
This causes Xamarin to put the following into the generated AndroidManifest.xml file during the build (you can find this in the \\obj\\Debug\\android directory) 这会导致Xamarin在构建期间将以下内容放入生成的AndroidManifest.xml文件中(您可以在\\ obj \\ Debug \\ android目录中找到它)
<service android:icon="@drawable/icon" android:label="AndroidBatteryService" android:name="md55...1a.AndroidBatteryService" />
I used a very similar piece of code in my app and it worked fine. 我在我的应用程序中使用了一段非常相似的代码并且工作正常。 (Although you've probably worked this out by now.)
(虽然你现在可能已经解决了这个问题。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.