Java Android:推送通知将不起作用

时间:2019-03-03 21:21:21

标签: 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());
}

1 个答案:

答案 0 :(得分:0)

您必须为新的Android版本设置频道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并创建频道