Android8.0以上的notification和startForeground
阿新 • • 發佈:2018-12-10
1,startForeground方法,避免service被殺死
private void setNotification(String text) { Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); Notification notification = null; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { Uri mUri = Settings.System.DEFAULT_NOTIFICATION_URI; NotificationChannel mChannel = new NotificationChannel(CHANNEL_ONE_ID, "driver", NotificationManager.IMPORTANCE_LOW); mChannel.setDescription("description"); mChannel.setSound(mUri, Notification.AUDIO_ATTRIBUTES_DEFAULT); mManager.createNotificationChannel(mChannel); notification = new Notification.Builder(this, CHANNEL_ONE_ID) .setChannelId(CHANNEL_ONE_ID) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(getString(R.string.app_name)) .setContentText(text) .setContentIntent(pi) .build(); } else { // 提升應用許可權 notification = new Notification.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(getString(R.string.app_name)) .setContentText(text) .setContentIntent(pi) .build(); } notification.flags = Notification.FLAG_ONGOING_EVENT; notification.flags |= Notification.FLAG_NO_CLEAR; notification.flags |= Notification.FLAG_FOREGROUND_SERVICE; startForeground(10000, notification); }
2,8.0普通通知(新增channelID)
if (ScreenKt.isBackground(getActivity()) && isOnDuty) { //"您現在是出車中,進入後臺超過5分鐘可能會導致接不到單,請及時回到應用" SpeechKt.speak(R.string.enter_the_background); Intent intent = new Intent(getActivity(), MainActivity.class); PendingIntent pi = PendingIntent.getActivity(getActivity(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); Notification notification = null; NotificationManager manager = (NotificationManager) getActivity().getSystemService(NOTIFICATION_SERVICE); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { String CHANNEL_ONE_ID = "com.huanqiuchuxing.driver"; Uri mUri = Settings.System.DEFAULT_NOTIFICATION_URI; NotificationChannel mChannel = new NotificationChannel(CHANNEL_ONE_ID, "driver", NotificationManager.IMPORTANCE_LOW); mChannel.setDescription("description"); mChannel.setSound(mUri, Notification.AUDIO_ATTRIBUTES_DEFAULT); manager.createNotificationChannel(mChannel); notification = new Notification.Builder(getActivity(), CHANNEL_ONE_ID) .setChannelId(CHANNEL_ONE_ID) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("您現在是出車中,進入後臺超過5分鐘可能會導致接不到單,請及時回到應用") .setContentText("進入應用") .setAutoCancel(true) .setContentIntent(pi) .build(); } else { notification = new Notification.Builder(getActivity()) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("您現在是出車中,進入後臺超過5分鐘可能會導致接不到單,請及時回到應用") .setContentText("進入應用") .setAutoCancel(true) .setContentIntent(pi) .build(); } manager.notify(10001, notification); }
親測有效,拿走不謝。