版权声明:一起学习,一起进步 https://blog.csdn.net/qq_15623599/article/details/88817095
Service stopForeground(false);
/**
* 通知作成
*/
private void createNotification() {
// Android8以上通知表示
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Context context = getApplicationContext();
Intent openUi = new Intent(context, MainActivity.class);
openUi.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
openUi.setAction(Intent.ACTION_MAIN);
openUi.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0x01, openUi, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, mAppName, NotificationManager.IMPORTANCE_DEFAULT);
if (null != notificationManager) {
notificationManager.createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setContentTitle(mAppName)
.setSmallIcon(android.R.drawable.ic_media_play)
.setContentText("MyMediaPlay")
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setWhen(System.currentTimeMillis())
.build();
//开启前台服务这样系统就不会随意杀死这个服务,通知也不会消失
startForeground(1, notification);
}
}
}
startForeground(1, notification);
开启前台服务,通知栏中该通知也会变为不会随着点击或者滑动而删除。除非该service结束停止,这个通知也会随之被删除。
stopForeground(false);
这个是结束前台的服务,通知栏中该通知会随着点击或者滑动而删除。参数是:是否删除之前发送的通知,true:删除。false:不删除 (用手滑动或者点击通知会被删除)