我每15分钟监测一次用户的位置,即使用户在任务栏中关闭应用程序,我也希望该应用程序继续发送位置。
我尝试了这个示例,但它是针对Xamarin.Androidhttps://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services。我需要创建一个依赖服务,但我不知道如何操作。
我每15分钟监测一次用户的位置,即使用户在任务栏中关闭应用程序,我也希望该应用程序继续发送位置。
我尝试了这个示例,但它是针对Xamarin.Androidhttps://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services。我需要创建一个依赖服务,但我不知道如何操作。
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();
}