我正在尝试在Android startForegroundService()
及更高版本的设备中启动O
。
服务开始了。在服务的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);
答案 0 :(得分:0)
从Android O通知开始,应指定NotificationChannel
,否则将不会显示,并且错误将出现在日志中。
答案 1 :(得分:0)
解决方案:
步骤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分别是int
和string
变量。
第二步:将其附加到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) {
....
}
已推荐,有关更多信息,请参见Here
希望有帮助。
答案 2 :(得分: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")