我必须创建一个依赖服务,但我不知道如何。
首先,在 Xamarin.forms 项目中创建一个Interface:
public interface IStartService
{
void StartForegroundServiceCompat();
}
然后在xxx.Android项目中新建一个文件我们叫itstartServiceAndroid来实现你想要的服务:
[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
}
}
}
一旦你想在Xamarin.forms项目中调用StartForegroundServiceCompat方法,你可以使用:
public MainPage()
{
InitializeComponent();
//call method to start service, you can put this line everywhere you want to get start
DependencyService.Get<IStartService>().StartForegroundServiceCompat();
}
这是关于dependency-service的文档
对于 iOS,如果用户在任务栏中关闭应用程序,您将无法再运行任何服务。如果应用正在运行,你可以阅读这篇关于ios-backgrounding-walkthroughs/location-walkthrough的文档