撒网要见鱼
撒网要见鱼
  • 发布:2016-01-06 18:57
  • 更新:2023-07-21 14:52
  • 阅读:19367

【分享】一个Notification 进度条插件(android,NJS实现,直接就可使用)

分类:HTML5+

如题,分享一个Notification 进度条插件(android,用js调用原生api实现,直接就可以使用).
参考1: http://ask.dcloud.net.cn/article/155
参考2:http://ask.dcloud.net.cn/question/2464

详细介绍: 最近有一个需求是,android更新资源包时,需要在通知栏里显示下载进度条,于是就搜索了下已有的解决方案
发现并没有现成的解决方案,于是参考了以上两个解决方案,结合了下,实现了直接能调用的js插件.

第一步(分析以上两种方案的缺陷):
第一种:功能上能实现需求,但是使用起来太麻烦,而且也不方便调试(需要离线打包后才能看到效果),
而且,我这里还遇到了一个问题,在 hbuild 6.9.2 中,我明明已经添加了自定义模块权限,但是却一直提示我 ***权限没有添加, 真的是把我弄的吐血了, 所以没办法,只能另谋他路.

第二种:使用起来很方便,但是却没有完全达到功能要求(只显示了普通通知,但没有显示进度条),而且在api <16 的机子上会报错.
于是在这个基础上,结合第一种方法.写了一个 工具类,实现android的通知栏控制(兼容了api11-16的通知显示)

源码:

/**  
 * @description njs实现android原生功能   
 * 1.通知栏消息  
 * @see http://ask.dcloud.net.cn/article/503  
 *   
 * @author dailc  
 * @version 1.0  
 * @time 2016-01-08 08:38:20  
 */  
(function(obj) {  
    var defaultTitle = '通知栏标题';  
    var defaultContent = '通知内容';  
    var defaultTicker = '通知提示';  
    var defaultNotifyId = 1000;  
    var defaultNumber = 1;  
    /**  
     * plusReady  
     * @param {type} callback  
     * @returns {Window}  
     */  
    obj.plusReady = function(callback) {  
        if (window.plus) {  
            setTimeout(function() { //解决callback与plusready事件的执行时机问题(典型案例:showWaiting,closeWaiting)  
                callback();  
            }, 0);  
        } else {  
            document.addEventListener("plusready", function() {  
                callback();  
            }, false);  
        }  
        return this;  
    };  
    /**  
     * @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;  
        }  
    };  
    /**  
     * @description 通过push功能来推送消息  
     */  
    obj.sendNotificationByPush = function() {  
        var options = {  
            cover: false  
        };  
        var str = ": 欢迎使用Html5 Plus创建本地消息!";  
        plus.push.createMessage(str, "LocalMSG", options);  
    };  
    (function() {  
        /**  
         * @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);  
                //设为true代表常驻状态栏  
                this.mNotificationBuild.setOngoing(false);  
                this.mNotificationBuild.setContentTitle(defaultTitle);  
                this.mNotificationBuild.setContentText(defaultContent);  
                this.mNotificationBuild.setTicker(defaultTicker);  
                //默认的push图标  
                this.mNotificationBuild.setSmallIcon(17301620);  
                //设置默认声音  
                //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 || '正在下载';  
            content = content || '正在下载';  
            tickerTips = tickerTips || '进度提示';  
            //          tickerTips = tickerTips || defaultTicker;  
            this.mNotificationBuild.setContentTitle(title);  
            this.mNotificationBuild.setContentText(content);  
            this.mNotificationBuild.setTicker(tickerTips);  
            //进度条显示时,默认无声音  
            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 || '进度条显示完毕';  
            content = content || '进度条显示完毕';  
            tickerTips = tickerTips || '进度提示';  
            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();  
            }         
        };  
        obj.plusReady(function() {  
            obj.NotificationUtil = new NotificationCustom();  
        });  
    })();  

})(window.NjsPhoneApi = {});

调用方法示例:
显示普通通知:

NjsPhoneApi.NotificationUtil.setNotification('测试标题'+staticI,'测试内容');

显示进度条代码:

function testProgress() {  
        //插件调用  
        NjsPhoneApi.NotificationUtil.setNotification("新版下载", "开始下载");  
        var current = 0;  
        NjsPhoneApi.NotificationUtil.setProgress(current); //插件调用  
        function progress() {  
            setTimeout(function() {  
                current += 1;  
                NjsPhoneApi.NotificationUtil.setProgress(current);  
                if(current>=100){  
                     NjsPhoneApi.NotificationUtil.compProgressNotification("下载完成");  
                }else{  
                    progress();  
                }  
            }, 100);  
        };  
        progress();  
    };  
testProgress();//调用显示进度条

取消单条通知:(传入参数为id,不传采用默认id)

NjsPhoneApi.NotificationUtil.clearNotification();

取消所有通知:

NjsPhoneApi.NotificationUtil.clearAllNotification();

另外: 支持自定义id的通知,也就是说可以通过传入不同的id,同时显示不同的通知

效果图1:
效果图2:
示例源码:鉴于有一些朋友会有各式各样的奇怪错误,所以这里单独写了一个示例,测试了android机型(华为,联想)都是可以正常使用的.
示例源码中采用的是默认id

18 关注 分享
蔡繁荣 郑家好人 w***@163.com BirdZhang 雪之梦技术驿站 gaus z***@163.com ws初学者 internetdc 7***@qq.com 漠 1***@qq.com 8***@qq.com q***@126.com 3***@qq.com aliang888 我想和你在一起 一抱一个胖猪猪

要回复文章请先登录注册

小权

小权

最近发现一个问题,根据下载状态在通知栏实时显示下载进度是没问题,但是这个会阻止其他webview打开。也就是说通知栏下载时,app内其他webview都打不开了。不知哪里的问题?
2020-01-16 10:24
小权

小权

以前用过没问题,最近换了个华为手机,安卓9,已经显示不了通知了。不知道是什么问题,js里面已经执行了
2019-12-11 23:59
2***@qq.com

2***@qq.com

回复 2***@qq.com :
```
<script>
import util from './util.js'
var appname='智慧工地'+'-V'+'1.0.0'
var NotificationUtil=util.NotificationUtil()//实例创建
NotificationUtil.setNotification(appname, "开始下载! ");
```
2019-10-30 16:10
2***@qq.com

2***@qq.com

//在通知栏显示下载进度条
```
//util.js
export util=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 || '进度提示';
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();
}
```

//下面是调用方法:(其中有些函数名是我封装后的名字,你可以根据具体功能找到plus里的函数)
```
<script>
import util from './util.js'
var appname='智慧工地'+'-V'+'1.0.0'
var NotificationUtil=util.Notification()//实例创建
NotificationUtil.setNotification(appname, "开始下载! ");
//dtask就是plus.createDownload
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();
})
break;
default: //5: (Number 类型 )下载任务已暂停 -1: (Number 类型 )枚举任务状态
console.log("Download failed: " + status);
NotificationUtil.compProgressNotification(appname,"下载失败! ");
break;
}
} );
</script>
```
2019-10-30 16:07
水沟小鱼

水沟小鱼

回复 2***@qq.com :
怎么引用NotificationUtil() ?在uni里不知道怎么用啊!!!
2019-10-30 15:17
2***@qq.com

2***@qq.com

//在通知栏显示下载进度条
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 || '进度提示';
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();
},



下面是调用方法:(其中有些函数名是我封装后的名字,你可以根据具体功能找到plus里的函数)
var appname=(target.AppName||info.name)+'-V'+result.root.version
var NotificationUtil=target.$api.Notification()//实例创建
NotificationUtil.setNotification(appname, "开始下载! ");
//dtask就是plus.createDownload
var dtask = target.$api.dtask(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=await target.$api.install(target.$api.locFile(task.filename))
if(!ins) target.$api.fail(Err.insFail);
NotificationUtil.clearNotification();
break;
default: //5: (Number 类型 )下载任务已暂停 -1: (Number 类型 )枚举任务状态
console.log("Download failed: " + status);
NotificationUtil.compProgressNotification(appname,"下载失败! ");
break;
}
} );
2019-10-23 17:59
y***@163.com

y***@163.com

回复 2***@qq.com :
请问一下如何改的 ,求解
2019-10-23 15:57
2***@qq.com

2***@qq.com

很实用,已经改版用到uniapp,安卓荣耀9很稳定
2019-10-22 11:19
g***@126.com

g***@126.com

android8以上好像都不行
2019-09-24 15:07
t***@163.com

t***@163.com

这个功能很强大,如果要做点击回调。要怎么调?
2019-08-19 10:16