-1

我正在尝试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);
4

3 回答 3

0

解决方案:

第一步:创建一个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) {
    ....
}

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

希望能帮助到你。

于 2018-10-31T11:31:58.897 回答
0

从 Android 版本的 Oreo 开始,您必须将频道添加到您的通知中,如下所示:

private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    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);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

并为这样的通知创建对象:

Notification.Builder notification = new Notification.Builder(this, "CHANNEL_ID")
于 2018-10-31T12:42:39.773 回答
0

从 Android O 开始,通知应该有NotificationChannel指定,否则它们将不会显示并且错误会出现在日志中。

您可以在此处阅读有关通知通道的更多信息,以及在此处了解 Api 26+ 中的前台服务的更多信息

于 2018-10-31T11:21:00.557 回答