首页 > 解决方案 > 通知不可见或未到来

问题描述

我正在尝试startForegroundService()在 androidO及以上设备中启动。

服务开始了。在onCreate()服务的方法中,我添加了startForeground()with 通知。

但是通知没有来。我无法看到它。

我在onCreate()服务方法中的代码:

  Notification.Builder builder = new Notification.Builder(this, "1")
          .setContentTitle(getString(R.string.app_name))
          .setContentText("in app filling")
          .setAutoCancel(true);

  Notification notification = builder.build();
  startForeground(1, notification);

标签: androidandroid-notificationsandroid-8.0-oreoforegroundnotification

解决方案


解决方案:

第一步:创建一个NotificationChannel

NotificationChannel notificationChannel = new NotificationChannel(channel_id , channel_name, NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.enableLights(true);
            notificationChannel.enableVibration(true);
            notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});

这里,channel_id 和 channel_name 分别是intstring变量。

第2步:将其附加到NotificationManager

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);

第 3 步:创建您的通知:

NotificationCompat.Builder notification = new NotificationCompat.Builder(this, "channel_id")
                        .setContentTitle("Test Title")
                        .setContentText("Test Message")
                        .setSmallIcon(R.mipmap.ic_launcher);

Step4:在同一个NotificationManager对象中附加通知

notificationManager.notify(1, notification.build());

最后,进行检查以通知它是否高于 Android O:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    ....
}

参考和更多关于这个可以找到这里

希望能帮助到你。


推荐阅读