Android 8.0+ 通知不顯示的適配

最近在 寫項目的時候  發現 通知並不會顯示的問題,查看資料發現 從Android 8.0開始通知必須加上ChannelId android

Android O 引入了 通知渠道(Notification Channels),以提供統一的系統來幫助用戶管理通知,若是是針對 android O 爲目標平臺時,必須實現一個或者多個通知渠道,以向用戶顯示通知。好比聊天軟件,爲每一個聊天組設置一個通知渠道,指定特定聲音、燈光等配置
String id = "my_id";
String name="my_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);
相關文章
相關標籤/搜索