DCMarvel
DCMarvel
  • 发布:2021-11-28 16:04
  • 更新:2023-04-12 11:15
  • 阅读:920

Android 音乐通知栏Native.js版本!

分类:Native.js

代码

const androidNotifi = {  
  NotifyID: 237,  
  receiver:null,  
  NotifiService:null,  
  serv: null,  
  intent: null,  
  mNotificationBuild: null,  
  mediaBtn: null,  
  channelID : '1',  
  channelName : '音乐通知',  
  notifiImg:{},  
  getImgTemp: function(audioImage) {  
    return new Promise(resolve => {  
      if (this.notifiImg[encodeURIComponent(audioImage)]) {  
        return resolve(plus.io.convertLocalFileSystemURL(this.notifiImg[encodeURIComponent(audioImage)]));  
      }  
      if(!/^http/.test(audioImage)) {  
        this.notifiImg[encodeURIComponent(audioImage)] = audioImage ? audioImage : '_www/static/image/notifimusic.png';  
        return resolve(plus.io.convertLocalFileSystemURL(audioImage ? audioImage : '_www/static/image/notifimusic.png'));  
      }  
      uni.downloadFile({  
        url: audioImage,  
        complete: res => {  
          this.notifiImg[encodeURIComponent(audioImage)] = res.tempFilePath ? res.tempFilePath : '_www/static/image/notifimusic.png';  
          return resolve(plus.io.convertLocalFileSystemURL(res.tempFilePath ? res.tempFilePath : '_www/static/image/notifimusic.png'));  
        }  
      });  
    });  
  },  
  hideNotifi: function(server = false){  
    this.main&&this.receiver&&this.main.unregisterReceiver(this.receiver);   
    server&&this.serv&&this.serv.stopForeground&&this.serv.stopForeground(this.NotifyID, this.mNotificationBuild) ;  
    if (Number(plus.os.version.split('.')[0])>= 8){     
      this.NotifiService&&this.NotifiService.cancel&&this.NotifiService.cancel(this.channelID,this.NotifyID);   
    } else {      
      this.NotifiService&&this.NotifiService.cancel&&this.NotifiService.cancel(this.NotifyID);   

    }   
    this.receiver = null;  
    this.NotifiService = null;  
    this.serv = null;  
    this.intent = null;  
    this.mNotificationBuild = null;  
    // this.NotifiService&&this.NotifiService.cancelAll&&this.NotifiService.cancelAll();  
    this.mediaBtn ? this.mediaBtn.release() : ''; // 线控销毁  
  },  
  showNotifi:async function(param) {  
    if (uni.$_sko.systemInfo.platform != 'android') {   
      return;  
    }  
    try{  
      param = Object.assign({  
        title : '通知标题',  
        subTitle: '',  
        cont : '通知内容',  
        isPlay: true, // 媒体播放按钮  
        legIcon : plus.io.convertLocalFileSystemURL('_www/static/image/notifimusic.png'),  
        Ongoing : false,    // 不可删除  
      },param);  
      this.main = this.main ? this.main : plus.android.runtimeMainActivity();    
      var Context = plus.android.importClass("android.content.Context");    
      var BitmapFactory = plus.android.importClass("android.graphics.BitmapFactory");    
      var NotificationManager = plus.android.importClass("android.app.NotificationManager");  
      var Notification = plus.android.importClass("android.app.Notification");;    
      var Intent = plus.android.importClass("android.content.Intent");    
      var PendingIntent = plus.android.importClass("android.app.PendingIntent");    
      var androidR = plus.android.importClass("android.R");    
      this.NotifiService = this.NotifiService ? this.NotifiService : this.main.getSystemService(Context.NOTIFICATION_SERVICE);    
      this.intent = this.intent ? this.intent : new Intent(this.main, this.main.getClass());    
      var UNI_MEDIA_BROAD = this.main.getPackageName() + '.mediaBtn';  

      //PendingIntent.getActivity的第二个参数需要设置为随机数,否则多个通知时会导致前面的通知被后面的通知替换Extra的数据    
      var pendingIntent = PendingIntent.getActivity(this.main, 0, this.intent, PendingIntent.FLAG_CANCEL_CURRENT);    
      var firstVersionNumber = Number(plus.os.version.split('.')[0]);    
      var mNotification;    
       //判断当前系统版本在8.0及以上    
      if (firstVersionNumber >= 8){  
          if (this.NotifiService.getNotificationChannel() == null){    
              var NotificationChannel = plus.android.importClass('android.app.NotificationChannel');    
              var channel = new NotificationChannel(this.channelID, this.channelName, NotificationManager.IMPORTANCE_HIGH);      
              this.NotifiService.createNotificationChannel(channel);      
              plus.android.autoCollection(NotificationChannel);  
          }    
          param.callBack&&this.main.startForegroundService(this.intent);  
          mNotification = new Notification.Builder(this.main, this.channelID);    
      } else {      
          mNotification = new Notification.Builder(this.main);      
          param.callBack&&this.main.startService(this.intent);  
      }      

      if(param.callBack) {  
        mNotification.addAction(androidR.drawable.ic_media_previous, "prev", PendingIntent.getBroadcast(this.main, 0, new Intent().setAction(UNI_MEDIA_BROAD + '.prev'), PendingIntent.FLAG_CANCEL_CURRENT));  
        mNotification.addAction((param.isPlay ? androidR.drawable.ic_media_pause : androidR.drawable.ic_media_play), "play", PendingIntent.getBroadcast(this.main, 0, new Intent().setAction(UNI_MEDIA_BROAD + '.play'), PendingIntent.FLAG_CANCEL_CURRENT));  
        mNotification.addAction(androidR.drawable.ic_media_next, "next", PendingIntent.getBroadcast(this.main, 0, new Intent().setAction(UNI_MEDIA_BROAD + '.next'), PendingIntent.FLAG_CANCEL_CURRENT));  
        var mMediaStyle = new Notification.MediaStyle();  
        mMediaStyle.setShowActionsInCompactView(0, 1, 2);  
        mNotification.setStyle(mMediaStyle);  
      }  
      mNotification.setOngoing(param.Ongoing);        
      param.legIcon&&mNotification.setLargeIcon(BitmapFactory.decodeFile(await this.getImgTemp(param.legIcon)));  
       mNotification.setSmallIcon(param.callBack?androidR.drawable.stat_sys_headset:androidR.drawable.stat_notify_chat); //设置图标    
       mNotification.setContentTitle(param.title);//设置标题  
       mNotification.setContentText(param.cont); //设置内容    
       param.subTitle&&mNotification.setSubText(param.subTitle);        //子内容暂时去掉    
       // mNotification.setAutoCancel(true);       //设置点击消失    
       //  mNotification.setShowWhen(true);         //显示通知时间    
       mNotification.setTicker("PadInfo");       //弹出通知    
       mNotification.setDefaults(Notification.DEFAULT_ALL);    
       // mNotification.setPriority(Notification.PRIORITY_DEFAULT);   //通知优先级      
       // mNotification.flags=Notification.FLAG_ONLY_ALERT_ONCE;     //发起通知时震动      
       mNotification.setContentIntent(pendingIntent);      

       this.mNotificationBuild = mNotification.build();  
       if (firstVersionNumber>= 8){      
         this.NotifiService.notify(this.channelID, this.NotifyID, this.mNotificationBuild);        
       } else {      
         this.NotifiService.notify(this.NotifyID, this.mNotificationBuild);      
       }   
       if(param.callBack) {  
          this.main&&this.receiver&&this.main.unregisterReceiver(this.receiver);   
          this.receiver = this.receiver ? this.receiver : plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {    
            onReceive: function(context, intent) { //实现onReceiver回调函数    
              param.callBack(intent.getAction().replace(UNI_MEDIA_BROAD + '.',''));    
            }    
          });   
        var IntentFilter = plus.android.importClass('android.content.IntentFilter');    
        var filter = new IntentFilter();    
        filter.addAction(UNI_MEDIA_BROAD + '.prev');  
        filter.addAction(UNI_MEDIA_BROAD + '.play');  
        filter.addAction(UNI_MEDIA_BROAD + '.next');  
        this.main.unregisterReceiver(this.receiver);  
        this.main.registerReceiver(this.receiver, filter); //注册监听    
        this.mediaBtn = uni.requireNativePlugin('uniMediaButton');  // 监听线控  需要配合附件中的插件( Android API >= 26)  
        this.mediaBtn.initMediaButton(res => {  
           console.log(res.message);  
          // 绑定失败/销毁  
          if(res.code == '-1') {  
            this.mediaBtn = null;  
            return;  
          }  
           // res.keyAction == 1 按键松开 res.keyAction == 0 按键按下 播放按钮肯能只有按下  
          if(res.keyCode && res.keyAction == '0') {  
            switch (res.keyCode){  
              case 88:  
                param.callBack(  
                  'prev'  
                );  
                break;  
              case 87:  
                param.callBack(  
                  'next'  
                );  
                break;  
              case 127:  
              case 126:  
                param.callBack(  
                  'play'  
                );  
                break;  
            }  
          }  
        });  
        var serv = plus.android.importClass("android.app.Service");  
        this.serv = this.serv ? this.serv : new serv();  
        this.serv.startForeground(this.NotifyID, this.mNotificationBuild);  
        plus.android.autoCollection(serv);  
        plus.android.autoCollection(IntentFilter);  
       }  
      plus.android.autoCollection(Context);  
      plus.android.autoCollection(BitmapFactory);  
      plus.android.autoCollection(NotificationManager);  
      plus.android.autoCollection(Notification);  
      plus.android.autoCollection(Intent);  
      plus.android.autoCollection(PendingIntent);  
      plus.android.autoCollection(androidR);  
      plus.android.autoCollection(this.receiver);  

    }catch(e){  
      console.log(e);  
    }  
  }  
};

使用方法

// 开启 - 更新标题/播放(暂停)按钮  
show();  
function show(){  
    androidNotifi.showNotifi({  
        title : '通知标题',  
        subTitle: '通知小标题',  
        cont : '通知内容',  
        isPlay: true, // 媒体播放按钮状态(控制播放/暂停按钮样式)  
        legIcon : '', // 封面图片  
        Ongoing : false,    // 是否可删除  
        callBack:function(res){  
            switch (res){  
            case 'play':  
        console.log('play');  
        break;  
        case 'prev':  
        console.log('prev');  
        break;  
        case 'next':  
        console.log('next');  
        break;  
        }  
        }  
    })  
}  
// 关闭  
function hide(){  
    androidNotifi.hideNotifi();  
}  

由于Android播放视频没有通知栏控制.开始一直使用XZH-musicNotification 的插件,但是由于版本更新,出现BUG(插件已更新).
但是不能总等插件更新,就自己动动手写了一个Native.js版本,由于手上设备不多,没有测试更多的兼容性.在这里希望大家能勇于使用修改提出问题,完善此通知提示!
附件是线控耳机、蓝牙耳机按键监听插件(API >= 26,X86好像不支持忘了)

4 关注 分享
工程狮 include5943 tuonioooo s***@innovatech.net.cn

要回复文章请先登录注册

9***@qq.com

9***@qq.com

方便留下联系方式么,有些不太懂
2023-04-12 11:15