通知欄開發與適配Android8.0
阿新 • • 發佈:2018-12-08
1.Android通知欄在專案開發中,還是用的比較多的,一般是這三個步驟來做Android通知欄:
(1)獲取通知欄管理器物件
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
(2)建立通知物件,並設定ui
NotificationCompat.Builder builder = new NotificationCompat.Builder(GlobalApplication.globalContext);
builder.setSmallIcon(R.drawable.smalleIcon);
builder.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(),R.drawable.largeIcon));
builder.setContentTitle(title); //通知欄標題
builder.setContentText(progress + "%"); //通知欄內容
builder.setTicker("新訊息"); //顯示在狀態列
Notification notification = builder.build();
(3)傳送通知
mNotificationManager.notify(id,notification);
2.通知欄的其他api
(1)通知欄的移除:mNotificationManager.cancle(id); //該id需要同傳送通知的id一致
(2)點選事件處理:
// 構建一個Intent Intent resultIntent = new Intent(NotificationActivity.this, TestActivity.class); resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); // 封裝一個PendingIntent PendingIntent resultPendingIntent = PendingIntent.getActivity(NotificationActivity.this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); // 設定通知主題的意圖 builder.setContentIntent(resultPendingIntent);
3.注意問題:
(1)使用系統樣式必須設定三個屬性,否則崩潰。
setContentText()
setContentTitle()
setSmallIcon()
(2)下載更新進度時,必須控制更新頻率(或者不設定largeIcon),否則部分手機(nexus)會導致記憶體溢位崩潰。我們可以定時更新,這樣進度會跳躍式前進,市場上大部分都是這麼做的。
private NotificationCompat.Builder getNotification(String title, int progress) {
//設定通知的標題
builder.setContentTitle(title);
if (progress >= 0) {
//當progress大於或等於0時,才需要顯示下載進度
MyLogUtil.i(TAG + "---getNotification--progress:" + progress);
builder.setContentText(progress + "%");
builder.setProgress(100, progress, false);
}
return builder;
}
(3)自定義通知欄樣式時,問題更多,且適配是個問題(背景色各不一致),一般還是不建議這麼做了。
在使用remoteView時,layout需要注意控制元件的使用(只能是AnalogClock,Button,Chronometer,ImageButton,mageView,ProgressBar,TextView這7種),且寬度必須為0,wrap_content,或match_parent,fill_parent不可用。
4.適配Android8.0
(1) android 8.0中通知欄必須設定channel,否則無法展示。
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(false); //是否在桌面icon右上角展示小紅點
channel.setShowBadge(false); //是否在久按桌面圖示時顯示此渠道的通知
channel.enableVibration(false);
channel.setSound(null, null);
mNotificationManager.createNotificationChannel(channel);
}
builder = new NotificationCompat.Builder(context, channelId);
channelId為整數字符串,channelName最好使用漢字,因為通知欄上右滑出現設定按鈕,點開設定按鈕,可以看到這個通知
channalName.
(2)狀態列圖示問題
builder.setSmallIcon(R.drawable.smalleIcon); 可以設定狀態列圖示。但是該圖示有一定要求,除了主幹部分,其他地方需要透明,否則在顯示時會是一個深灰色的矩形。