Android 8.0 適配——發(fā)送通知

前言

Android 8.0對通知欄進行了比較大的改動,引入了通知渠道的概念,發(fā)出通知的時候,可以根據(jù)渠道來發(fā)送,目的是提高用戶體驗,方便用戶管理通知信息,同時也提高了通知到達率。同時用戶具有管理每個渠道的權限(設置聲音、震動等),并且可以關閉某個渠道的通知。

官方說明

關于8.0之后的一些變更,具體可以參考地址(需科學上網(wǎng)):
https://developer.android.google.cn/about/versions/oreo/android-8.0-changes
關于8.0之后的通知功能重新設計的說明:
https://developer.android.google.cn/about/versions/oreo/android-8.0

通知.png

通知適配

先來看看8.0之前是如何發(fā)送通知的
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = null;
Intent intent = new Intent(context, SecondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, REQUEST_CODE_NOTIFY, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification = new Notification.Builder(context)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                        .setContentTitle("API 24")
                        .setContentText("消息內容")
                        .setContentIntent(pendingIntent)
                        .setAutoCancel(true)
                        .setWhen(System.currentTimeMillis())
                        .build();
notificationManager.notify(123, notification);

但是這段代碼在8.0之后的機器上就無法發(fā)送通知,會提示沒有指定通知渠道


錯誤.png
接下來看看8.0之后是如何適配的

其實核心就是要給每個通知指定通知渠道,這樣通知才可以正常發(fā)送,通知展示的方式取決于用戶的設置

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = null;
Intent intent = new Intent(context, SecondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, REQUEST_CODE_NOTIFY, intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    String id = "渠道ID";
    String channelName = "渠道A";
    NotificationChannel channel = new NotificationChannel(id, channelName, NotificationManager.IMPORTANCE_HIGH);
    notificationManager.createNotificationChannel(channel);
    notification = new Notification.Builder(context, id)
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                            .setContentTitle("API 26")
                            .setContentText("渠道A")
                            .setContentIntent(pendingIntent)
                            .setAutoCancel(true)
                            .setWhen(System.currentTimeMillis())
                            .build();
}
notificationManager.notify(123, notification);

結尾

以上就是8.0之后發(fā)送通知時要注意的地方,可以使用Build.VERSION.SDK_INT >= Build.VERSION_CODES.O來判斷一下手機的版本來選擇發(fā)送的方式,避免產(chǎn)生一些不必要的錯誤提示。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容