startForegroundService() did not then call Service.startForeground()
程序员文章站
2022-05-28 23:30:59
...
项目在部分9.0手机运行报错:startForegroundService() did not then call Service.startForeground()
查资料发现:是因为8.0以上系统不允许后台应用启动后台服务。所以需要把后台服务设置为前台服务。
并且修改service启动函数。
Intent intent = new Intent(getApplicationContext(), PlayerMusicService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startService(intent);
}
在service的onCreate中加入
if (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的其他属性可以参考如下:
Intent intent;
//点击通知栏消息跳转页
intent = new Intent(context, TargetDetailsActivity.class);
NotificationManager 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);
下一篇: eclipse总结(二)--常见问题