通知不可见或不来



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

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

但通知并没有到来。我看不见。

我在服务的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);

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

您可以在这里阅读更多关于通知渠道和Api 26+前台服务的信息。

解决方案:

步骤1:创建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);

步骤4:在同一NotificationManager对象中附加通知

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

最后,如果它高于Android O:,请进行检查以通知

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

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

希望能有所帮助。

从Android版本的奥利奥,你必须将频道添加到你的通知中,如下所示:

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")

相关内容

  • 没有找到相关文章

最新更新