要在Android 9.0上使用Xamarin Android中的服务,您可以按照以下步骤进行操作:
创建一个新的Xamarin Android项目或打开现有项目。
在项目中创建一个新的类,该类将作为服务的基类。命名为MyService.cs(您可以根据自己的需求更改名称)。
using Android.App;
using Android.Content;
using Android.OS;
namespace YourNamespace
{
[Service]
public class MyService : Service
{
public override IBinder OnBind(Intent intent)
{
return null;
}
public override void OnCreate()
{
base.OnCreate();
// 在此处执行服务初始化操作
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
// 在此处执行后台操作
return StartCommandResult.Sticky;
}
public override void OnDestroy()
{
base.OnDestroy();
// 在此处执行服务销毁操作
}
}
}
var serviceIntent = new Intent(Application.Context, typeof(MyService));
Application.Context.StartService(serviceIntent);
var serviceIntent = new Intent(Application.Context, typeof(MyService));
Application.Context.StopService(serviceIntent);
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Task.Run(() =>
{
// 在此处执行后台操作
});
return StartCommandResult.Sticky;
}
这样,您就可以在Android 9.0上使用Xamarin Android中的服务了。请根据自己的需求进行相应的修改和扩展。