Xamarin Android 创建前台服务的个人粗略总结
简要及注意事项
简要
1.前台服务需要创建通知,面向8.0需要事先创建通知管道
2.8.0启动前台服务需要使用StartForegroundService而不是StartServer
3.在服务中需要调用StartForeground传入一个通知对象将自己注册为前台服务
注意事项
服务本身还会受到下面一些因素的影响
1.是否允许后台活动,
2.是否忽略电池优化
创建通知管道
创建最简单最粗略的通知管道的方法,主要的参数是管道id,创建通知时要使用
public static void CreateNotificationChannel(ContextWrapper context, string channelID, string channelName) { if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { ((NotificationManager)context.GetSystemService(Context.NotificationService)) .CreateNotificationChannel(new NotificationChannel(channelID, channelName, NotificationImportance.Default)); } }
创建通知
下面是创建通知的简化方法, 一个通知标题,文本,图标,一个前台服务貌似必须设置为True的项, 通知管道id在NotificationCompat.Builder构造函数填入
public static Notification CreateServerNotification(string contentTitle, string contentText, Context context, string channelID) { return new NotificationCompat.Builder(context, channelID) .SetContentTitle(contentTitle) .SetContentText(contentText) .SetSmallIcon(Resource.Mipmap.icon) .SetOngoing(true) .Build(); }
开启服务的办法
android 8.0及以上版本开启前台服务需要使用StartForegroundService
public static void StartServer(ContextWrapper context, Intent intent) { context.StartForegroundService(intent); }
服务的声明
[Service] public sealed class MyServer : Service { public override void OnCreate() { base.OnCreate(); const int NOTIFICATION_ID = 345; const string CHANNEL_ID = "自己起一个id"; const string CHANNEL_NAME = "自己起一个name"; CreateNotificationChannel(this, CHANNEL_ID, CHANNEL_NAME); var notification = CreateServerNotification("标题", "内容", this, CHANNEL_ID); StartForeground(NOTIFICATION_ID, notification); } [return: GeneratedEnum] public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId) { return StartCommandResult.NotSticky; } public override void OnDestroy() { base.OnDestroy(); } public override IBinder OnBind(Intent intent) { return null; } }
参考文档
关于服务
https://developer.android.google.cn/guide/components/services
https://docs.microsoft.com/zh-cn/xamarin/android/app-fundamentals/services/
关于通知
https://developer.android.google.cn/guide/topics/ui/notifiers/notifications
浙公网安备 33010602011771号