如何管理通知管理器null



当我发送通知时,时间通知管理器显示为空,我如何处理?

private void sendNotification(String title, String message, String msgTitle) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(Config.CHANNEL_ID, name, importance);
channel.setDescription(description);
notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}

此处通知管理器为null。

Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = 
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new 
NotificationCompat.Builder(this, Config.CHANNEL_ID)
.setSmallIcon(R.drawable.logo_4)
.setContentTitle(msgTitle)
.setContentText(message)
.setChannelId(Config.CHANNEL_ID)
.setSound(defaultSoundUri)
.setPriority(Notification.PRIORITY_HIGH)
.addAction(R.drawable.folder, "OPEN", pendingIntent);
Objects.requireNonNull(notificationManager).notify(getRequestCode(), 
notificationBuilder.build());

尝试下面的代码,它对您有效:

Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder;
builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.cum_small_icon)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setCustomContentView(remoteViews)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);

builder.setDefaults(NotificationCompat.DEFAULT_SOUND | NotificationCompat.DEFAULT_LIGHTS | NotificationCompat.DEFAULT_VIBRATE);
createNotificationChannel();
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
notificationManagerCompat.notify(code, builder.build());

createNotificationChannel((

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}

您可以这样初始化notificationManager

notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

最新更新