我是靠谱客的博主 谦让世界,这篇文章主要介绍startForegroundService() did not then call Service.startForeground(),现在分享给大家,希望可以做个参考。
项目在部分9.0手机运行报错:startForegroundService() did not then call Service.startForeground()
查资料发现:是因为8.0以上系统不允许后台应用启动后台服务。所以需要把后台服务设置为前台服务。
并且修改service启动函数。
复制代码
1
2
3
4
5
6Intent intent = new Intent(getApplicationContext(), PlayerMusicService.class); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForegroundService(intent); } else { startService(intent); }
在service的onCreate中加入
复制代码
1
2
3
4
5if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Notification noti = new Notification(); noti.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT; startForeground(1, noti); }
有部分人说有时候还是会报错,可以在onStart 中再加入一遍startForeground。(没有遇到不知道真伪)
如需要设置Notification的其他属性可以参考如下:
复制代码
1
2
3Intent intent; //点击通知栏消息跳转页 intent = new Intent(context, TargetDetailsActivity.class);
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // Intent para disparar o broadcast PendingIntent p = PendingIntent.getActivity(context, type, intent, PendingIntent.FLAG_UPDATE_CURRENT); // Cria a notification NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setContentIntent(p) .setContentTitle(title) .setContentText(txt) .setSmallIcon(R.drawable.ic_notifications_black_24dp) .setVisibility(Notification.VISIBILITY_PUBLIC) .setPriority(NotificationCompat.PRIORITY_MAX) .setAutoCancel(true) .setSound(Uri.parse(""))//设置空的声音和震动,否则华为手机不显示悬浮通知 // .setDefaults(NotificationCompat.DEFAULT_ALL)//通知栏提示音、震动、闪灯等都设置为默认 .setVibrate(new long[]{0}); // Dispara a notification Notification n = builder.build(); manager.notify(type, n);
最后
以上就是谦让世界最近收集整理的关于startForegroundService() did not then call Service.startForeground()的全部内容,更多相关startForegroundService()内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复