首页 > 解决方案 > Java android:推送通知不起作用

问题描述

当我在我的 android 应用程序上运行它以尝试使用以下命令获取通知时:sendNotification("test","title",1);

我收到一个错误:E/NotificationManager: notifyAsUser: tag=null, id=1, user=UserHandle{0}

private void sendNotification(String message, String title, int id) {
    Intent intent = new Intent(this, Game.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */,
            intent, PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.maintitle)
            .setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

    notificationManager.notify(id /* ID of notification */,
            notificationBuilder.build());
}

标签: javaandroid

解决方案


您必须为新的 android 版本设置 Channel id。以这种方式创建您的通知

private final static String CHANNEL_ID = "my_notification";
private void sendNotification(String message, String title, int id) {
        Intent intent = new Intent(this, Game.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */,
                intent, PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.maintitle)
                .setContentTitle(title)
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "news_notification", NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(id /* ID of notification */,
                notificationBuilder.build());
    }

在 NotificationCompat.Builder 中设置 CHANNEL_ID 并创建通道


推荐阅读