Android 8.0以下及8.0以上通知欄創(chuàng)建,
private NotificationManager mNotifyManager;
private Notification.Builder builder;
private NotificationChannel channel = null;
int id = 1;
開始創(chuàng)建:
mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//ChannelId為"1",ChannelName為"Channel1"
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
System.out.println("當(dāng)前為8.0以上版本");
channel = new NotificationChannel("1",
"Channel1", NotificationManager.IMPORTANCE_DEFAULT);
//是否在桌面icon右上角展示小紅點(diǎn)
channel.enableLights(true);
//小紅點(diǎn)顏色
channel.setLightColor(Color.GREEN);
//是否在久按桌面圖標(biāo)時顯示此渠道的通知
channel.setShowBadge(true);
mNotifyManager.createNotificationChannel(channel);
//與channelId對應(yīng)
builder = new Notification.Builder(getApplicationContext(), "1");
builder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("內(nèi)容下載")
.setContentText("下載中掂恕,請騷等")
//久按桌面圖標(biāo)時允許的此條通知的數(shù)量
.setNumber(3);
} else {
System.out.println("當(dāng)前為8.0以下版本");
builder = new Notification.Builder(this);
builder.setContentTitle("內(nèi)容下載")
.setContentText("下載中拖陆,請稍等")
.setSmallIcon(R.mipmap.ic_launcher);
}
下載開始,顯示通知欄懊亡,
System.out.println("下載開始");
//開始時候依啰,初始化進(jìn)度條
builder.setProgress(100, 0, false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mNotifyManager.notify(id, builder.build());
}
下載完成,更新通知欄店枣,
System.out.println("下載完成");
//成功后將setProgress的兩個變量設(shè)置為0速警,progress就會消失叹誉。setProgerss第三個參數(shù)的含義是,如果 能確定進(jìn)度條執(zhí)行的時間闷旧,就傳入true长豁,否則是false,此處直接傳入false即可忙灼。
builder.setProgress(0, 0, false).setContentText("已經(jīng)下載完成");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mNotifyManager.notify(id, builder.build());
}
下載中匠襟,更新通知欄進(jìn)度條,
//更新進(jìn)度條
int currentNum = (int) (100 * currentProgress / percent);
System.out.println("/n下載進(jìn)度百分比為:" + currentNum + "下載進(jìn)度值為:" + currentProgress + "/n下載總大小為:" + percent);
builder.setProgress(100, currentNum, false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mNotifyManager.notify(id, builder.build());
}
最后缀棍,清除通知欄宅此。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
System.out.println("當(dāng)前為8.0以上版本1");
mNotifyManager.deleteNotificationChannel("1");
}else{
System.out.println("當(dāng)前為8.0以下版本1");
//移除通知欄
mNotifyManager.cancel(id);
}
注:這里有點(diǎn)問題,就是在8.0上如果是下載文件的通知爬范,就會出現(xiàn)每更新一下進(jìn)度條就有一個提示音,目前的解決辦法就是在創(chuàng)建NotificationManager時設(shè)置低優(yōu)先級:
NotificationManager.IMPORTANCE_DEFAULT
image.png