startForegroundService() did not then call Service.startForeground()

項目在部分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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章