繁体   English   中英

状态栏通知未显示?

[英]Status Bar Notification Not Showing?

我有一个简单的方法,它的Button的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)中,所有通知都必须分配给一个频道。 这项工作对我来说:

    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'

您可以检查官方的Android文档

您的代码还可以。 但是由于您的目标是Android 8.0,因此您需要实现通知渠道,因为这是Android Oreo中的首选方式。

https://developer.android.com/guide/topics/ui/notifiers/notifications.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM