我有一个简单的方法,按钮的onclick()应该生成状态栏通知,但由于某种原因,它没有显示。
public void createNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setContentTitle("Notification!")
.setContentText("This is my first notification!");
Notification notification = builder.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, notification);
}
答案 0 :(得分:3)
在Android 8(API级别26)中,必须将所有通知分配给频道。 这项工作对我来说:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getContext(), CHANNEL_ID)
.setSmallIcon(R.drawable.emo_no_paint_120)
.setContentTitle("title")
.setContentText("content")
.setColor(Color.parseColor("#009add"))
.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(
NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(mChannel);
}
notificationManager.notify(0, mBuilder.build());
您应该添加AppCompat库
implementation 'com.android.support:support-compat:27.1.0'
答案 1 :(得分:0)
您的代码没问题。但由于您的目标是Android 8.0,因此您需要实施通知渠道,因为这是Android Oreo中的首选方式。
https://developer.android.com/guide/topics/ui/notifiers/notifications.html