安卓通知栏显示下载进度(兼容安卓8.0系统)

实现的功能:使用下载框架下载文件,下载的进度通过eventbus发送,期间遇到了在安卓8.0系统上通知栏不显示的问题

一、创建通知的时候,要对安卓8.0系统特殊处理

1.先声明好需要用到的成员变量

private NotificationManager mNotifyMgr;
private PendingIntent contentIntent;
private Notification.Builder builder;
public String NOTIFICATION_CHANNEL_ID = "notification_id";
private static final int NO_3 = 0x3;

2.创建Notification

//这里要特殊处理一下安卓8.0的Notification
    private void initNotifications() {
        mNotifyMgr= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //点击标题栏会跳转到哪个页面
        contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "APP_NAME", NotificationManager.IMPORTANCE_HIGH);
            //设置静音,但是一些设备貌似不起作用(华为pad就不行,还是会有提示音)
            channel.setSound(null,null);
            if (mNotifyMgr != null) {
                mNotifyMgr.createNotificationChannel(channel);
            }
            builder = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID);
            builder.setContentTitle("标题");
            builder.setContentText("内容");
            builder.setSmallIcon(R.drawable.icon);
            //因为会频繁更新下载进度,所以这样设置之后,提示音只会提示一次
            builder.setOnlyAlertOnce(true);
        } else {
            builder = new Notification.Builder(this);
            if(Build.VERSION.SDK_INT >= 21) {
                builder.setSound(null,null);
            }
            builder.setContentTitle("标题");
            builder.setContentText("内容");
            builder.setSmallIcon(R.drawable.icon);
            builder.setDefaults(Notification.DEFAULT_LIGHTS);
            builder.setOnlyAlertOnce(true);
        }
        builder.setContentIntent(contentIntent);
    }

3.根据接收到的eventbus,来设置通知栏

@Subscribe(threadMode = ThreadMode.MAIN)
    public void downLoadMsg(DownloadStateEvent downloadStateEvent) {
        switch (downloadStateEvent.getDownloadState()) {
            case start:
            	//下载开始,显示通知栏
                mNotifyMgr.notify(NO_3, builder.build());
                break;
            case progress:
            //设置通知栏下载进度
                builder.setProgress(100, downloadStateEvent.getProgress(), false);
                mNotifyMgr.notify(NO_3, builder.build());
                break;
            case error:
            //下载失败
                mNotifyMgr.cancel(NO_3);//设置关闭通知栏
                break;
            case finish:
            //下载完成
                mNotifyMgr.cancel(NO_3);//设置关闭通知栏
                break;
            default:
                break;
        }
    }

使用该api需要minSdkVersion最低位16

上一篇:Jenkins(Extended E-mail Notification)邮箱配置正确但是并没有发送邮件


下一篇:【HTML】HTML5中的Web Notification桌面通知