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); 可以設置狀態欄圖標。但是該圖標有一定要求,除了主幹部分,其他地方需要透明,否則在顯示時會是一個深灰色的矩形。