1. 程式人生 > >解決Android 8.0 的Notification不顯示問題

解決Android 8.0 的Notification不顯示問題

Notification在android 8.0以上設定時,需要設定渠道資訊才能夠正常顯示通知。本以為很簡單,上網查了很多資料都不行,後面決定自己去看Notifacation的原始碼,終於找到了解決方案,在這裡和大家做個分享。廢話不多說,直接上程式碼:

String id = "my_channel_01";
String name="我是渠道名字";
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
    Toast.makeText(this, mChannel.toString(), Toast.LENGTH_SHORT).show();
    Log.i(TAG, mChannel.toString());
    notificationManager.createNotificationChannel(mChannel);
    notification = new Notification.Builder(this)
            .setChannelId(id)
            .setContentTitle("5 new messages")
            .setContentText("hahaha")
            .setSmallIcon(R.mipmap.ic_launcher).build();
} else {
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setContentTitle("5 new messages")
            .setContentText("hahaha")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setOngoing(true)
            .setChannel(id);//無效
    notification = notificationBuilder.build();
}
notificationManager.notify(111123, notification);