android - 状态栏通知不显示?

标签 android notificationmanager

我有一个简单的方法,按钮的 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);
}

最佳答案

在 Android 8(API 级别 26)中,所有通知都必须分配给一个 channel 。 这对我有用:

    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'

你可以查看 official Android Docs

关于android - 状态栏通知不显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46818810/

相关文章:

Android:如何对通知触摸事件使用react?

android - 如何解决 "No Activity found to handle Intent"错误

android - 在 android 中调用 getInflater() 时出现 StackOverflowError 异常

android-如何检查本地 Sqlite 数据库中的新数据并持续推送通知?

android - 调用Web服务时出错

java - Android firestore,从 Documentsnapshot 列表中获取键和值

android - 单击后如何正确清除所有通知?

android - 如何在状态栏的特定位置添加通知/正在进行的事件图标?

Android 通知消息(不)从 Activity 切换

android - GCM 推送通知。已发布错误通知 - 无法扩展 : StatusBarNotification 的 RemoteViews