简体   繁体   中英

Status Bar Notification Not Showing?

I have a simple method which onclick() of a Button should generate status bar notification, but for some reason, it isn't showing up.

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);
}

In Android 8 (API level 26), all notifications must be assigned to a channel. This work for me:

    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());

And you should add AppCompat library

implementation 'com.android.support:support-compat:27.1.0'

You could check official Android Docs

Your code is okay. But since you are targeting Android 8.0, you need to implement Notification Channels since this the preferred way in Android Oreo.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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