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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lylddingHFFW/article/details/78219327

原文链接:http://blog.csdn.net/lylddinghffw/article/details/78219327

源码分析 : https://blog.csdn.net/lylddingHFFW/article/details/80366791

前台服务测试app地址:https://github.com/lyldding/foregroundservice

记录场景:Android 8.0 有一项复杂功能;系统不允许后台应用创建后台服务。 因此,Android 8.0 引入了一种全新的方法,即 Context.startForegroundService(),以在前台启动新服务。
在系统创建服务后,应用有5秒5秒5秒5秒5秒的时间来调用该服务的 startForeground() 方法以显示新服务的用户可见通知。如果应用在此时间限制内未调用 startForeground(),则系统将停止服务并声明此应用为 ANR。

但是目前在调用:context.startForegroundService(intent)时报如下ANR,startForegroundService()文档说明在service启动后要调用startForeground()。

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

**解决方案:**使用startForegroundService启动服务后,在service的onCreate方法中调用startForeground()。

NotificationChannel channel = new NotificationChannel(CHANNEL_ID,CHANNEL_NAME,
                NotificationManager.IMPORTANCE_HIGH);

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);

Notification notification = new Notification.Builder(getApplicationContext(),CHANNEL_ID).build();
startForeground(1, 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

前台服务测试app地址:https://github.com/lyldding/foregroundservice

猜你喜欢

转载自blog.csdn.net/lylddingHFFW/article/details/78219327