在Android O上启动Service遇到问题记录

记录场景:Android 8.0 有一项复杂功能;系统不允许后台应用创建后台服务。 因此,Android 8.0 引入了一种全新的方法,即 Context.startForegroundService(),以在前台启动新服务。

在系统创建服务后,应用有五秒的时间来调用该服务的 startForeground() 方法以显示新服务的用户可见通知。如果应用在此时间限制内未调用 startForeground(),则系统将停止服务并声明此应用为 ANR。

但是目前在调用:context.startForegroundService(intent)时报如下ANR,startForegroundService()文档说明在service启动后能够自动调用startForeground(),不知为何没有调用?如有大神知道请告知,谢谢。

android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()

于是使用context.startService(intent),并在在service的onCreate方法中调用startForeground(),主动将其变为前台服务。

NotificationChannel channel = new NotificationChannel("id","name", NotificationManager.IMPORTANCE_LOW);

NotificationManager manager = (NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE); 

manager.createNotificationChannel(channel);

Notification notification = new Notification.Builder(service,"id").build();

startForeground(id, notification);

在api 26 中要使用Notification.Builder(Context, String) ,并且要指明 NotificationChannel 的Id. 如果不加则会提示:Developer warning for package XXX,Failed to post notification on channel “null”.

当然关于NotificationChannel的配置可以参考:https://developer.android.google.cn/reference/android/app/NotificationChannel.html

Notification.Builder参考:https://developer.android.google.cn/reference/android/app/Notification.Builder.html

你可能感兴趣的:(在Android O上启动Service遇到问题记录)