我必须创建一个依赖服务,但我不知道如何创建。
首先,创建一个Interface
在 Xamarin.forms 项目中:
public interface IStartService
{
void StartForegroundServiceCompat();
}
然后创建一个新文件我们称之为itstartServiceAndroid
在xxx.Android项目中实现你想要的服务:
[assembly: Dependency(typeof(startServiceAndroid))]
namespace DependencyServiceDemos.Droid
{
public class startServiceAndroid : IStartService
{
public void StartForegroundServiceCompat()
{
var intent = new Intent(MainActivity.Instance, typeof(myLocationService));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
{
MainActivity.Instance.StartForegroundService(intent);
}
else
{
MainActivity.Instance.StartService(intent);
}
}
}
[Service]
public class myLocationService : Service
{
public override IBinder OnBind(Intent intent)
{
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
// Code not directly related to publishing the notification has been omitted for clarity.
// Normally, this method would hold the code to be run when the service is started.
//Write want you want to do here
}
}
}
一旦您想致电StartForegroundServiceCompat
中的方法Xamarin.forms
项目,您可以使用:
public MainPage()
{
InitializeComponent();
//call method to start service, you can put this line everywhere you want to get start
DependencyService.Get<IStartService>().StartForegroundServiceCompat();
}
这是有关的文档依赖服务 https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/dependency-service/
对于iOS,如果用户关闭任务栏中的应用程序,则将无法再运行任何服务。如果应用程序正在运行,您可以阅读此文档ios 背景演练/位置演练 https://learn.microsoft.com/en-us/xamarin/ios/app-fundamentals/backgrounding/ios-backgrounding-walkthroughs/location-walkthrough