通知栏显示下载进度—版本更新

项目需求:版本更新在系统通知栏显示下载进度,且不能阻塞页面的正常操作。

1. 参考

(1) 使用native.js在安卓通知栏显示下载进度条原生通知栏下载进度条通知概览Android开发中Notification通知栏的基本用法8.0通知栏新增通知渠道

//通知栏中实时显示进度条会引起操作界面卡顿
        testNotification:function(){
            
            //Uni.Push:标准基座下可直接运行;自定义基座或正式包,需在manifest.json添加Uni.Push模块并配置
            // plus.push.createMessage( "下载中...", "jack",{cover:true,sound:"none",title:"标题",subtitle:"副标题"});
            
            var appname='杰克物联';
            var NotificationUtil = NotifiUtil();//实例创建
            NotificationUtil.setNotification(appname, "开始下载! ");
            //dtask就是plus.createDownload
            var url = "https://www.uchat.com.cn/app/iot/JackIot.apk";
            var dtask = plus.downloader.createDownload(url);// POST请求提交数据
            dtask.start();
            dtask.addEventListener( "statechanged", async function(task,status){
                switch(task.state) {
                    case undefined: //下载任务未开始
                    case 0: //下载任务开始调度
                    case 1: //下载任务开始请求
                    case 2: break; //下载任务请求已经接收
                    case 3: // 已接收到数据
                        NotificationUtil.setProgress(Math.round(task.downloadedSize/task.totalSize*100),appname);
                        break;
                    case 4: // 下载完成
                        console.log("Download success: " + task.filename);
                        NotificationUtil.compProgressNotification(appname,"下载完成! ");
                        // var ins = plus.runtime.install(plus.io.convertLocalFileSystemURL(task.filename), {force: force},()=>{
                        //  uni.showToast({icon:'none',title:'安装成功!'});
                        //  NotificationUtil.clearNotification();
                        // },(e)=>{
                        //  uni.showToast({icon:'none',title:'安装失败!'});
                        //  NotificationUtil.clearNotification();
                        // })
                        plus.runtime.install(task.filename);  // 安装下载的apk文件  
                        break;
                    default: //5: (Number 类型 )下载任务已暂停 -1: (Number 类型 )枚举任务状态
                        console.log("Download failed: " + status);
                        NotificationUtil.compProgressNotification(appname,"下载失败! ");
                        break;
                }
            });
        },

(2) 本地消息推送的实现1: 使用NJS控制Android通知栏,不用个推实现本地消息推送(Local Notification)

var NotifyID = 1;  
            var Context = plus.android.importClass("android.content.Context");  
            var main = plus.android.runtimeMainActivity();  
            var Noti = plus.android.importClass("android.app.Notification");  
            var NotificationManager = plus.android.importClass("android.app.NotificationManager");  
            var nm = main.getSystemService(Context.NOTIFICATION_SERVICE)  
            var Notification = plus.android.importClass("android.app.Notification");  
            var mNotification = new Notification.Builder(main);  
            mNotification.setOngoing(true);  
            mNotification.setContentTitle("Hbuilder")  
            mNotification.setContentText("MUI & 5+ 大好!")  
            mNotification.setSmallIcon(17301620)  
            mNotification.setTicker("PadInfo")  
            
            mNotification.setNumber(10)  
            var mNb = mNotification.build()  
            nm.notify(NotifyID , mNb);

(3) 本地消息推送的实现2: 创建本地消息
备注:正式包需配置UniPush模块,参考UniPush使用指南

plus.push.createMessage( "下载中...", "jack",{cover:true,sound:"none",title:"标题",subtitle:"副标题"});//仅在通知栏显示开始和结束提醒:不会引起操作界面卡顿

(4) Downloader模块管理网络文件下载任务plus.downloader.createDownload和uni.downloadFile 执行一个任务的时候 app锁屏后重启卡死,导致app提示关闭应用或等待H5+MUI,plus.downloader下载函数 会照成页面卡顿偶尔甚至卡死无响应的问题(附件即可下载实例代码)

2. 实现需求

(1) notification.js源码

  //js文件格式是GBK,在调用时手机上汉字会出现乱码,请大家在使用时复制粘贴一份,另存为UTF-8的文件格式,注意其中汉字显示是否正常,注释信息无所谓
    //util.js原来是GRK格式(通知栏中会显示乱码),需重新复制一份,uniapp中js文件默认是UFT-8格式:将复制后的js文件中的中文乱码修改即可使用
    //在通知栏显示下载进度条
export default function NotificationUtil(){
        var defaultTitle = '通知栏标题';
        var defaultContent = '通知内容';
        var defaultTicker = '通知提示';
        var defaultNotifyId = 1000;
        var defaultNumber = 1;
        /**
         * @description 比较两个版本大小
         * 比较版本大小,如果新版本nowVersion大于旧版本OldResourceVersion则返回true,否则返回false
         */
        function compareVersion(OldVersion, nowVersion) {
            if (!OldVersion || !nowVersion || OldVersion == '' || nowVersion == '') {
                return false;
            }
            //第二份参数 是 数组的最大长度
            var OldVersionA = OldVersion.split(".", 4);
            var nowVersionA = nowVersion.split(".", 4);
            for (var i = 0; i < OldVersionA.length && i < nowVersionA.length; i++) {
                var strOld = OldVersionA[i];
                var numOld = parseInt(strOld);
                var strNow = nowVersionA[i];
                var numNow = parseInt(strNow);
                //小版本到高版本
                if (numNow > numOld /*||strNow.length>strOld.length*/ ) {
                    return true;
                } else if (numNow < numOld) {
                    return false;
                }
            }
            //如果是版本  如 1.6 - 1.6.1
            if (nowVersionA.length > OldVersionA.length && 0 == nowVersion.indexOf(OldVersion)) {
                return true;
            }
        };
        /**
         * @constructor 创建通知栏进度条构造函数
         */
        function NotificationCustom() {
            if (plus.os.name != 'Android') {
                return;
            }
            //当前版本号
            var SystemVersion = plus.os.version;
            var Context = plus.android.importClass("android.content.Context");
            var main = plus.android.runtimeMainActivity();
            var NotificationManager = plus.android.importClass("android.app.NotificationManager");
            var nm = main.getSystemService(Context.NOTIFICATION_SERVICE)
            // Notification build 要android api16以上才能使用(4.1.2以上)
            var Notification = null;
            if (compareVersion('4.1.1', SystemVersion) == true) {
                Notification = plus.android.importClass("android.app.Notification");
            } else {
                Notification = plus.android.importClass("android.support.v4.app.NotificationCompat");
            }
            if (Notification) {
                this.notifyManager = nm;
                this.mNotificationBuild = new Notification.Builder(main);
                /*
                mBuilder.setContentTitle("测试标题")//设置通知栏标题
                        .setContentText("测试内容") //设置通知栏显示内容
                        .setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL)) //设置通知栏点击意图
                        //  .setNumber(number) //设置通知集合的数量
                        .setTicker("测试通知来啦") //通知首次出现在通知栏,带上升动画效果的
                        .setWhen(System.currentTimeMillis())//通知产生的时间,会在通知信息里显示,一般是系统获取到的时间
                        .setPriority(Notification.PRIORITY_DEFAULT) //设置该通知优先级
                        //  .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
                        .setOngoing(false)//ture,ַ设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
                        .setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合
                        //Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加声音 // requires VIBRATE permission
                        .setSmallIcon(R.drawable.ic_launcher);//设置通知小ICON
                */
                //设为true代表常驻状态栏
                this.mNotificationBuild.setOngoing(false);
                this.mNotificationBuild.setContentTitle(defaultTitle);
                this.mNotificationBuild.setContentText(defaultContent);
                this.mNotificationBuild.setTicker(defaultTicker);
                //默认的push图标
                // this.mNotificationBuild.setSmallIcon(17301620);//设置小图标
                //https://www.cnblogs.com/penghuster/p/4909930.html
                var R = plus.android.importClass("android.R");
                this.mNotificationBuild.setSmallIcon(R.drawable.stat_sys_download);
                //设置默认声音
                // console.log('默认:'+plus.android.importClass("android.app.Notification").DEFAULT_SOUND);
                this.mNotificationBuild.setDefaults(plus.android.importClass("android.app.Notification").DEFAULT_SOUND);
                //this.mNotificationBuild.setNumber(defaultNumber)
            }
        };
        /**
         * @description 给android通知栏发送通知
         * @param {String} title 标题
         * @param {String} content  内容
         * @param {String} tickerTips  提示
         * @param {Number} notifyId id,默认为1000
         */
        NotificationCustom.prototype.setNotification = function(title, content, tickerTips,notifyId) {
            if (this.mNotificationBuild == null ||
                this.notifyManager == null) {
                return;
            }
            notifyId = (typeof(notifyId)=='number')?notifyId:defaultNotifyId;
            title = title || defaultTitle;
            content = content || defaultContent;
            tickerTips = tickerTips || defaultTicker;
            this.mNotificationBuild.setContentTitle(title);
            this.mNotificationBuild.setContentText(content);
            this.mNotificationBuild.setTicker(tickerTips);
            //默认有声音
            this.mNotificationBuild.setDefaults(plus.android.importClass("android.app.Notification").DEFAULT_SOUND);
            this.notifyManager.notify(notifyId, this.mNotificationBuild.build());
        };
        /**
         * @description 设置进度条
         * @param {Number} progress
         * @param {String} title 标题
         * @param {String} content  内容
         * @param {String} tickerTips  提示
         * @param {Number} notifyId id,默认为1000
         */
        NotificationCustom.prototype.setProgress = function(progress, title, content, tickerTips,notifyId) {
            if (this.mNotificationBuild == null ||
                this.notifyManager == null) {
                return;
            }
            notifyId = (typeof(notifyId)=='number')?notifyId:defaultNotifyId;
            title = title || 'APP更新包';
            content = content || '正在下载...【'+progress+'%】';
            tickerTips = tickerTips || '进度提示';
            this.mNotificationBuild.setContentTitle(title);
            this.mNotificationBuild.setContentText(content);
            this.mNotificationBuild.setTicker(tickerTips);
            /*
            如果为确定的进度条:调用setProgress(max, progress, false)来设置通知,在更新进度的时候在此发起通知更新progress,并且在下载完成后要移除进度条,通过调用setProgress(0, 0, false)既可。
            如果为不确定(持续活动)的进度条,这是在处理进度无法准确获知时显示活动正在持续,所以调用setProgress(0, 0, true) ,操作结束时,调用setProgress(0, 0, false)并更新通知以移除指示条
            */
            //进度条显示时,默认无声音
            this.mNotificationBuild.setDefaults(0);
            this.mNotificationBuild.setProgress(100, progress, false);
            this.notifyManager.notify(notifyId, this.mNotificationBuild.build());
        };
        /**
         * @description 完成进度条
         * @param {String} title 标题
         * @param {String} content  内容
         * @param {String} tickerTips  提示
         * @param {Number} notifyId id,默认为1000
         */
        NotificationCustom.prototype.compProgressNotification = function(title, content, tickerTips,notifyId) {
            if (this.mNotificationBuild == null ||
                this.notifyManager == null) {
                return;
            }
            notifyId = (typeof(notifyId)=='number')?notifyId:defaultNotifyId;
            title = title || 'APP更新包';
            content = content || '下载完毕!';
            tickerTips = tickerTips || '进度提示';
            
            var R = plus.android.importClass("android.R");
            this.mNotificationBuild.setSmallIcon(R.drawable.stat_sys_download_done);
            
            this.mNotificationBuild.setContentTitle(title);
            this.mNotificationBuild.setContentText(content);
            this.mNotificationBuild.setTicker(tickerTips);
            this.mNotificationBuild.setProgress(0, 0, false);//移除进度条
            //默认有声音
            this.mNotificationBuild.setDefaults(plus.android.importClass("android.app.Notification").DEFAULT_SOUND);
            this.notifyManager.notify(notifyId, this.mNotificationBuild.build());
        };
        /**
         * @description 清除通知栏信息
         * @param {Number} notifyId id,默认为1000
         */
        NotificationCustom.prototype.clearNotification = function(notifyId) {
            notifyId = (typeof(notifyId)=='number')?notifyId:defaultNotifyId;
            if(this.notifyManager){
                this.notifyManager.cancel(notifyId);
            }       
        };
        /**
         * @description 清除所有通知栏信息
         */
        NotificationCustom.prototype.clearAllNotification = function() {
            if(this.notifyManager){
                this.notifyManager.cancelAll();
            }       
        };
        return new NotificationCustom();
    }

(2) 在test.vue中使用

import NotifiUtil from '@/common/notification/notification.js'

//版本升级:实现通知栏显示下载进度
        downloadApkAndShowProcessForUpdate:function(url){
            
            //Uni.Push:标准基座下可直接运行;自定义基座或正式包,需在manifest.json添加Uni.Push模块并配置
            // plus.push.createMessage( "下载中...", "jack",{cover:true,sound:"none",title:"标题",subtitle:"副标题"});//仅在通知栏显示开始和结束提醒:不会引起操作界面卡顿
            
            var appname='杰克物联';
            var NotificationUtil=NotifiUtil();//实例创建
            NotificationUtil.setNotification(appname, "开始下载! ");
            //dtask就是plus.createDownload
            //var url = "https://www.uchat.com.cn/app/iot/JackIot.apk";
            var dtask = plus.downloader.createDownload(url);// POST请求提交数据
            dtask.start();
            var arr = [{
                pro:1,
                isFirst:true
            },{
                pro:10,
                isFirst:true
            },{
                pro:30,
                isFirst:true
            },{
                pro:50,
                isFirst:true
            },{
                pro:70,
                isFirst:true
            },{
                pro:90,
                isFirst:true
            }]
            dtask.addEventListener( "statechanged", async function(task,status){
                switch(task.state) {
                    case undefined: //下载任务未开始
                    case 0: //下载任务开始调度
                    case 1: //下载任务开始请求
                    case 2: break; //下载任务请求已经接收
                    case 3: // 已接收到数据
                        // NotificationUtil.setProgress(Math.round(task.downloadedSize/task.totalSize*100),appname);//通知栏中实时更新进度条会引起操作界面卡顿:一秒执行40多次(监听函数),导致UI操作阻塞
                        var pro = parseInt(task.downloadedSize/task.totalSize*100);
                            // if(pro == 1 || pro == 10 || pro == 30 || pro == 50 || pro == 70 || pro == 90){//优化方案一:仅在指定整数进度时更新
                            //  console.log("进度:" + pro);
                            //  NotificationUtil.setProgress(pro,appname);
                            // }
                            switch (pro){//优化方案二:仅进度第一次出现(1,10,30,50,70,90)时刷新
                                case arr[0].pro:
                                    if(arr[0].isFirst){
                                        // console.log("进度:" + pro);
                                        NotificationUtil.setProgress(pro,appname);
                                        arr[0].isFirst = false;
                                    }
                                    break;
                                case arr[1].pro:
                                    if(arr[1].isFirst){
                                        // console.log("进度:" + pro);
                                        NotificationUtil.setProgress(pro,appname);
                                        arr[1].isFirst = false;
                                    }
                                    break;
                                case arr[2].pro:
                                    if(arr[2].isFirst){
                                        // console.log("进度:" + pro);
                                        NotificationUtil.setProgress(pro,appname);
                                        arr[2].isFirst = false;
                                    }
                                    break;
                                case arr[3].pro:
                                    if(arr[3].isFirst){
                                        // console.log("进度:" + pro);
                                        NotificationUtil.setProgress(pro,appname);
                                        arr[3].isFirst = false;
                                    }
                                    break;
                                case arr[4].pro:
                                    if(arr[4].isFirst){
                                        // console.log("进度:" + pro);
                                        NotificationUtil.setProgress(pro,appname);
                                        arr[4].isFirst = false;
                                    }
                                    break;
                                case arr[5].pro:
                                    if(arr[5].isFirst){
                                        // console.log("进度:" + pro);
                                        NotificationUtil.setProgress(pro,appname);
                                        arr[5].isFirst = false;
                                    }
                                    break;
                                default:
                                    break;
                            }
                            
                        
                        break;
                    case 4: // 下载完成
                        console.log("Download success: " + task.filename);
                        NotificationUtil.compProgressNotification(appname,"下载完成! ");
                        // var ins = plus.runtime.install(plus.io.convertLocalFileSystemURL(task.filename), {force: force},()=>{
                        //  uni.showToast({icon:'none',title:'安装成功!'});
                        //  NotificationUtil.clearNotification();
                        // },(e)=>{
                        //  uni.showToast({icon:'none',title:'安装失败!'});
                        //  NotificationUtil.clearNotification();
                        // })
                        plus.runtime.install(task.filename);  // 安装下载的apk文件  
                        break;
                    default: //5: (Number 类型 )下载任务已暂停 -1: (Number 类型 )枚举任务状态
                        console.log("Download failed: " + status);
                        NotificationUtil.compProgressNotification(appname,"下载失败! ");
                        break;
                }
            });
        },

3. 封装

(1) version.js

import NotifiUtil from './notification/notification.js'

const downloadAndHandleWgtFile = function(url){
    uni.downloadFile({
        url: url,  
        success: (downloadResult) => {  
            console.log("downLoadFile:" + JSON.stringify(downloadResult));
            if (downloadResult.statusCode === 200) {  
                plus.runtime.install(downloadResult.tempFilePath, {  
                    force: false  
                }, function() {  
                    console.log('install success...');  
                    plus.runtime.restart();  
                }, function(e) {  
                    console.error('install fail...');  
                });  
            }  
        }  
    });  
}

const downloadAndHandleApkFile = function(url){ 
    // plus.nativeUI.showWaiting("下载中..."); 
    uni.showToast({
        title: '下载中...',
        icon:'none'
    });
    plus.push.createMessage( "下载中...", "jack",{cover:true,sound:"none"});
    
    var dtask = plus.downloader.createDownload( url, {}, function ( d, status ) {  
        if ( status == 200 ) { // 下载成功 
            plus.push.createMessage( "下载完成", "jack",{cover:true});
            var path = d.filename;  
            console.log("path:" + d.filename);  
            plus.runtime.install(path);  // 安装下载的apk文件  
        } else {//下载失败  
            alert( "Download failed: " + status );   
        }   
        // plus.nativeUI.closeWaiting(); 
        // plus.push.clear();//清空系统消息中心所有的推送消息
    });  
    dtask.start();
}

//版本升级:实现通知栏显示下载进度
const downloadApkAndShowProgressForUpdate = function(url){
    // if(!hasNetwork()){
    //  return;
    // }
    
    // plus.push.createMessage( "下载中...", "jack",{cover:true,sound:"none",title:"标题",subtitle:"副标题"});//仅在通知栏显示开始和结束提醒:不会引起操作界面卡顿
    
    var appname='杰克物联';
    var NotificationUtil = NotifiUtil();//实例创建
    NotificationUtil.setNotification(appname, "开始下载! ");
    //dtask就是plus.createDownload
    // var url = "https://www.uchat.com.cn/app/iot/JackIot.apk";
    var dtask = plus.downloader.createDownload(url);// POST请求提交数据
    dtask.start();
    var arr = [{
        pro:1,
        isFirst:true
    },{
        pro:10,
        isFirst:true
    },{
        pro:30,
        isFirst:true
    },{
        pro:50,
        isFirst:true
    },{
        pro:70,
        isFirst:true
    },{
        pro:90,
        isFirst:true
    }]
    dtask.addEventListener( "statechanged", async function(task,status){
        switch(task.state) {
            case undefined: //下载任务未开始
            case 0: //下载任务开始调度
            case 1: //下载任务开始请求
            case 2: break; //下载任务请求已经接收
            case 3: // 已接收到数据
                // NotificationUtil.setProgress(Math.round(task.downloadedSize/task.totalSize*100),appname);//通知栏中实时更新进度条会引起操作界面卡顿:一秒执行40多次(监听函数),导致UI操作阻塞
                var pro = parseInt(task.downloadedSize/task.totalSize*100);
                    // if(pro == 1 || pro == 10 || pro == 30 || pro == 50 || pro == 70 || pro == 90){//优化方案一:仅在指定整数进度时更新
                    //  console.log("进度:" + pro);
                    //  NotificationUtil.setProgress(pro,appname);
                    // }
                    switch (pro){//优化方案二:仅进度第一次出现(1,10,30,50,70,90)时刷新
                        case arr[0].pro:
                            if(arr[0].isFirst){
                                // console.log("进度:" + pro);
                                NotificationUtil.setProgress(pro,appname);
                                arr[0].isFirst = false;
                            }
                            break;
                        case arr[1].pro:
                            if(arr[1].isFirst){
                                // console.log("进度:" + pro);
                                NotificationUtil.setProgress(pro,appname);
                                arr[1].isFirst = false;
                            }
                            break;
                        case arr[2].pro:
                            if(arr[2].isFirst){
                                // console.log("进度:" + pro);
                                NotificationUtil.setProgress(pro,appname);
                                arr[2].isFirst = false;
                            }
                            break;
                        case arr[3].pro:
                            if(arr[3].isFirst){
                                // console.log("进度:" + pro);
                                NotificationUtil.setProgress(pro,appname);
                                arr[3].isFirst = false;
                            }
                            break;
                        case arr[4].pro:
                            if(arr[4].isFirst){
                                // console.log("进度:" + pro);
                                NotificationUtil.setProgress(pro,appname);
                                arr[4].isFirst = false;
                            }
                            break;
                        case arr[5].pro:
                            if(arr[5].isFirst){
                                // console.log("进度:" + pro);
                                NotificationUtil.setProgress(pro,appname);
                                arr[5].isFirst = false;
                            }
                            break;
                        default:
                            break;
                    }
                break;
            case 4: // 下载完成
                console.log("Download success: " + task.filename);
                NotificationUtil.compProgressNotification(appname,"下载完成! ");
                // var ins = plus.runtime.install(plus.io.convertLocalFileSystemURL(task.filename), {force: force},()=>{
                //  uni.showToast({icon:'none',title:'安装成功!'});
                //  NotificationUtil.clearNotification();
                // },(e)=>{
                //  uni.showToast({icon:'none',title:'安装失败!'});
                //  NotificationUtil.clearNotification();
                // })
                plus.runtime.install(task.filename);  // 安装下载的apk文件  
                break;
            default: //5: (Number 类型 )下载任务已暂停 -1: (Number 类型 )枚举任务状态
                console.log("Download failed: " + status);
                NotificationUtil.compProgressNotification(appname,"下载失败! ");
                break;
        }
    });
}


export default {
    downloadAndHandleWgtFile,
    downloadAndHandleApkFile,
    downloadApkAndShowProgressForUpdate
}

(2) main.js

import Vue from 'vue'
import App from './App'

import Version from './common/version.js'

Vue.config.productionTip = false

Vue.prototype.Version = Version 

App.mpType = 'app'

const app = new Vue({
    Version,
    ...App
})
app.$mount()

(3) 在test.vue或App.vue中调用

this.Version.downloadApkAndShowProgressForUpdate(apkUrl);

4. 解决android8.0及以上通知不显示的问题

(1) 参考

(2) 修改notification.js(创建通知栏进度条构造函数)

this.notifyManager = nm;
this.mNotificationBuild = new Notification.Builder(main);

改为:

var Build = plus.android.importClass("android.os.Build");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//android8.0及以上需设置通知渠道才能显示通知
    //创建通知渠道
    var name = "渠道名称1";
    var description = "渠道描述1";
    var channelId="channelId1";//渠道id     
    // var importance = NotificationManager.IMPORTANCE_DEFAULT;//重要性级别
    var importance = NotificationManager.IMPORTANCE_HIGH;//重要性级别
    var NotificationChannel = plus.android.importClass("android.app.NotificationChannel");
    var mChannel = new NotificationChannel(channelId, name, importance);
    // var mChannel = new NotificationChannel("channelId1", "渠道名称1", importance);
    mChannel.setDescription(description);//渠道描述
    mChannel.setDescription("渠道描述1");//渠道描述
    mChannel.enableLights(true);//是否显示通知指示灯
    mChannel.enableVibration(true);//是否振动
    nm.createNotificationChannel(mChannel);//创建通知渠道
                        
    this.notifyManager = nm;
    this.mNotificationBuild = new Notification.Builder(main,channelId);
    // this.mNotificationBuild = new Notification.Builder(main,"channelId1");
}else{
    this.notifyManager = nm;
    this.mNotificationBuild = new Notification.Builder(main);
}

即:

/**
* @constructor 创建通知栏进度条构造函数
*/
function NotificationCustom() {
    if (plus.os.name != 'Android') {
        return;
    }
    //当前版本号
    var SystemVersion = plus.os.version;
    var Context = plus.android.importClass("android.content.Context");
    var main = plus.android.runtimeMainActivity();
    var NotificationManager = plus.android.importClass("android.app.NotificationManager");
    var nm = main.getSystemService(Context.NOTIFICATION_SERVICE)
    // Notification build 要android api16以上才能使用(4.1.2以上)
    var Notification = null;
    if (compareVersion('4.1.1', SystemVersion) == true) {
        Notification = plus.android.importClass("android.app.Notification");
    } else {
        Notification = plus.android.importClass("android.support.v4.app.NotificationCompat");
    }
    if (Notification) {
        // this.notifyManager = nm;
        // this.mNotificationBuild = new Notification.Builder(main);
                
        var Build = plus.android.importClass("android.os.Build");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//android8.0及以上需设置通知渠道才能显示通知
            //创建通知渠道
            var name = "渠道名称1";
            var description = "渠道描述1";
            var channelId="channelId1";//渠道id     
            // var importance = NotificationManager.IMPORTANCE_DEFAULT;//重要性级别
            var importance = NotificationManager.IMPORTANCE_HIGH;//重要性级别
            var NotificationChannel = plus.android.importClass("android.app.NotificationChannel");
            var mChannel = new NotificationChannel(channelId, name, importance);
            // var mChannel = new NotificationChannel("channelId1", "渠道名称1", importance);
            mChannel.setDescription(description);//渠道描述
            mChannel.setDescription("渠道描述1");//渠道描述
            mChannel.enableLights(true);//是否显示通知指示灯
            mChannel.enableVibration(true);//是否振动
            nm.createNotificationChannel(mChannel);//创建通知渠道
                        
            this.notifyManager = nm;
            this.mNotificationBuild = new Notification.Builder(main,channelId);
            // this.mNotificationBuild = new Notification.Builder(main,"channelId1");
        }else{
            this.notifyManager = nm;
            this.mNotificationBuild = new Notification.Builder(main);
        }
                
        /*
        mBuilder.setContentTitle("测试标题")//设置通知栏标题
            .setContentText("测试内容") //设置通知栏显示内容
            .setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL)) //设置通知栏点击意图
            //  .setNumber(number) //设置通知集合的数量
            .setTicker("测试通知来啦") //通知首次出现在通知栏,带上升动画效果的
            .setWhen(System.currentTimeMillis())//通知产生的时间,会在通知信息里显示,一般是系统获取到的时间
            .setPriority(Notification.PRIORITY_DEFAULT) //设置该通知优先级
            //  .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
            .setOngoing(false)//ture,ַ设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
            .setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合
            //Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加声音 // requires VIBRATE permission
            .setSmallIcon(R.drawable.ic_launcher);//设置通知小ICON
        */

        //设为true代表常驻状态栏
        this.mNotificationBuild.setOngoing(false);
        this.mNotificationBuild.setContentTitle(defaultTitle);
        this.mNotificationBuild.setContentText(defaultContent);
        this.mNotificationBuild.setTicker(defaultTicker);
        //默认的push图标
        // this.mNotificationBuild.setSmallIcon(17301620);//设置小图标
        //https://www.cnblogs.com/penghuster/p/4909930.html
        var R = plus.android.importClass("android.R");  
        this.mNotificationBuild.setSmallIcon(R.drawable.stat_sys_download);
        //设置默认声音
        // console.log('默认:'+plus.android.importClass("android.app.Notification").DEFAULT_SOUND);
        this.mNotificationBuild.setDefaults(plus.android.importClass("android.app.Notification").DEFAULT_SOUND);
        //this.mNotificationBuild.setNumber(defaultNumber)
    }
};

(3) 真机运行


小米11+Android11.png

说明:目前已发布为uniapp插件,有需要请移步Android系统通知通知栏显示进度条

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容