項目在部分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);