cordova功能点插件集成

之前在项目中经常用到cordova调用底层的方法,跟cordova打交道也有三年了,以下是我对于工作中是使用到的cordova功能插件整理

里面涉及到功能插件有更新、相机、打开系统相册、人脸识别、语音识别、指纹识别、蓝牙、通讯录、储存、定位、打开网络、分享(企业微信、qq、微信好友、微信朋友圈、微博、钉钉、支付宝)、录音、拨打电话、音量控制、屏幕亮度调节、截屏、录屏、消息推送、横竖屏、系统默认语言、扫描二维码。

部分功能由于ios系统权限问题无法在ios高版本上使用,测试apk和ipa也有线上的,需要的小伙伴可以联系我,兼容性和适配性通过Testin上已经做了大量的测试

目前插件涉及到的第三方平台为 fece-id(人脸识别)、腾讯budly(崩溃捕获)、友盟(应用统计)、微信(微信分享)、支付宝(支付宝分享)、qq(qq分享)、钉钉(钉钉分享)、微博(微博分享)、高德地图、百度地图(地图定位)、极光(消息推送)、企业微信(企业微信分享)、百度语音(语音识别)

//所有cordova插件都需要在index.html引入cordova.js和cordova_plugins.js

const cordovaFlag = true; // sdk开关
app = (function() {
  _this=this;
  return {
    initialize: function() {
      var u = navigator.userAgent;
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      if(isAndroid){
        return 'android'
      }else if(isiOS){
        return 'ios'
      };
      
    },
    camera:function(callback){

      if (cordovaFlag)
        var cameraOptions = {
          quality: 100,  // --图片质量,或者可以说图片的压缩比例,压缩后的图片可以减少存储空间和传输带宽,设置范围为0-100
          destinationType: Camera.DestinationType.DATA_URL,  //--目标类型,用来控制图片是以base64还是url的方式返回。
          sourceType: Camera.PictureSourceType.CAMERA,  // 定义函数如何获取图片取值有以下几种: Camera.PictureSourceType.CAMERA 使用摄像头来获 取; Camera.PictureSourceType.PHOTOLIBRARY  使用设备图库; Camera.PictureSourceType.SAVEDPHOTOALBUM 从已存相册中获取图片。
          allowEdit: true,  //--是否允许编辑,如果设置为true,用户可对图片进行缩小放大及滑动等操作来编辑图片。
          encodingType: Camera.EncodingType.JPEG,   //--告诉函数返回何种图片类型,支持的选项有JPEG和PNG.
          targetWdith: -1,   // --目标高度,决定函数将返回多大尺寸的图片,你可以设置targetWidth或者targetHeight中的任何一个,图片会据此进行缩放。如果你两个值都指定了,图片的缩放比例会根据最小的那个值进行缩放。无论哪种方式,长宽比都不会发生改变。
          targetHeight: -1,  //--目标宽度
          popoverOptions: CameraPopoverOptions,   //设置项调用相机自带的设置项
          correctOrientation:true,
          saveToPhotoAlbum: false   // -是否保存到本地相册中
        };
        function onCameraSuccess(data){
          callback && callback(data);
        };
        function onCameraError(res){
          alert('Failed because: ' + res);
        };
        navigator.camera.getPicture(onCameraSuccess, onCameraError, cameraOptions);
      // })
    },
    //访问设备的图像、音频录制和视频录制
    capture:function(callback){
      if (cordovaFlag)
      //duration参数为最长录制时间
      navigator.device.capture.captureVideo(onSuccess, onError, {duration: 20});
      function onSuccess(mediaFiles) {
        var i, path, len;
        for (i = 0, len = mediaFiles.length; i < len; i += 1) {
           path = mediaFiles[i].fullPath;
          //  alert("success\n" +
          //         "name:" + mediaFiles[i].name + "\n" +
          //         "size:" + mediaFiles[i].size + "\n" +
          //         "localURL:" + mediaFiles[i].localURL + "\n" +
          //         "fullPath:" + path);
            callback && callback(path);
        }
      };
      function onError(error) {
        console.log(error)
        alert('error' + error);
      }
    },
    //二维码扫码
    //success成功回调 error失败回调
    barcodeScanner:function(callback){
      if (cordovaFlag)
      cordova.plugins.barcodeScanner.scan(
        function(result){
          callback && callback(result.text)
        }, function(error){ 
          alert(error);
      });
    },
    //启动页设置
    //flag 为true时打开启动页 为false时关闭启动页
    splashscreen:function(flag){
      flag? navigator.splashscreen.show() : navigator.splashscreen.hide();
    },
    //获取app版本 添加插件cordova plugin add cordova-plugin-app-version
    getAppVersion:function(callback){
     cordova.getAppVersion.getVersionNumber().then(function (version){
          //获取当前app的版本号;
          callback && callback(version)
      });
    },
    //获取设备的硬件和软件信息 安装cordova plugin add cordova-plugin-device
    device:function(data){
      var message;
      switch(data){
        case 'cordova': //设备上运行的cordova版本信息
          message=device.cordova;
          break;
        case 'model': //设备的模型或产品的名称
          message=device.model;
          break;
        case 'platform':  //设备的操作系统名称。
          message=device.platform;
          break;
        case 'uuid':  //设备的全局惟一标识符
          message=device.uuid;
          break;
        case 'version': //操作系统版本号
          message=device.version;
          break;
        case 'manufacturer':  //设备的制造商
          message=device.manufacturer;
          break;
        case 'isVirtual': //是否运行在模拟器
          message=device.isVirtual;
          break;
        case 'serial':  //设备硬件序列号
          message=device.serial;
          break;
      };
      return message;
    },
    //联系人
    contacts:function(callback){
      var contact=[];
      var options = new ContactFindOptions();
      var fields = ["displayName", "phoneNumbers"];
      options.filter = "";
      options.multiple = true;
      options.hasPhoneNumber = true;
      // options.desiredFields = ["displayName", "phoneNumbers"];
    
      navigator.contacts.find(fields, function(contacts) {
        onSuccess(contacts);
      }, function onError(contactError) {
        alert(contactError);
      }, options);
      function onSuccess(contacts){
        alert(JSON.stringify(contacts));
        var contactsLength = contacts.length;
        for(var i = 0; i < contactsLength; i++) {
          // console.log('obj for '+i);
          var obj = {};
          app.initialize()=='android'?  obj.name = contacts[i].displayName : obj.name = contacts[i].name.formatted;
          if(contacts[i].phoneNumbers) obj.phoneNumbers = contacts[i].phoneNumbers[0].value;
          contact.push(obj);
          // contact = contact.concat([obj]);
          

          // _this.$set(contact, i, obj);
        };
        
        callback && callback(contact)
      }
    },
    //打开相册
    album:function(callback){
      "use strict"
      window.imagePicker.getPictures(function(results){
        callback && callback(results);
      }, function(error){
          alert('Error: ' + error);
      }, {
        maximumImagesCount: 9, //每次可选择图片数目
        quality: 90,  //图片质量
        outputType: 0
      }
      );
    },
    //打开蓝牙
    bluetooth:function(){
      if (cordovaFlag)
      if(this.initialize()=='android'){
        ble.enable(
            function() {
              alert("Bluetooth is enabled");
            },
            function() {
            alert("The user did *not* enable Bluetooth");
            });
      }else{
        this.jumpSet();
      } 
    },
    //音量控制
    //获取当前系统音量
    getCurrentVolume:function(onSuccess,onError){
      if (cordovaFlag) cordova.exec(onSuccess, onError, "Volume", "getCurrentVolume");
    },
    //设置音量
    changeVolume:function(onSuccess,onError,volumeProgress){
      // Volume.changeVolume(volumeProgress,onSuccess,onError)
      if (cordovaFlag) cordova.exec(onSuccess,onError,'Volume','changeVolume',[volumeProgress])
    },
    
    //拨打电话
    callNumber:function(onSuccess, onError, number){
      if (cordovaFlag) cordova.exec(onSuccess, onError, "CallNumber", "callNumber", [number, true]);
    },
    //旋转屏幕
    toggleScreen:function(){
      if (cordovaFlag)
      // alert(screen.orientation.type);
      //landscape-primary横屏 portrait-primary竖屏 
      
      screen.orientation.type=='portrait-primary' ? screen.orientation.lock('landscape') : screen.orientation.lock('portrait');
      // screen.orientation.unlock();
    },
    //查看联网类型
    //此插件只能监听网络的状态,并不能知道是否有真实的网络。部分情况如下:
    //4-1、手机欠费,数据流量开启,,返回的状态是CELL_2G 或 CELL_3G 或 CELL_4G ;
    //4-2,wifi有信号,实际没有网络。即路由器正常工作,没有插网线。返回状态“WiFi”
    //4-3,wifi有信号,但有权限,必须认证后才能连接。返回状态也是“wifi”
    //这三种情况下监听到的都是有网络的,实际没网络
    looknetwork:function(){
      if (cordovaFlag)
      var networkState = navigator.connection.type;
      var states = {};
      states[Connection.UNKNOWN]  = 'Unknown connection';
      states[Connection.ETHERNET] = 'Ethernet connection';
      states[Connection.WIFI]     = 'WiFi connection';
      states[Connection.CELL_2G]  = 'Cell 2G connection';
      states[Connection.CELL_3G]  = 'Cell 3G connection';
      states[Connection.CELL_4G]  = 'Cell 4G connection';
      states[Connection.CELL]     = 'Cell generic connection';
      states[Connection.NONE]     = 'No network connection';
      // alert('Connection type: ' + states[networkState]);
      return states[networkState];
    },
    //打开wifi
    toggleWifi:function(){
      if (cordovaFlag)
      if(this.initialize()=='android'){
        cordova.plugins.hotspot.toggleWifi(wifiStatus, errorCB);//取反函数,第一个参数可返回状态信息,若打开了wifi则返回true,反之false
          function wifiStatus(info){//判断返回的信息,若为true说明此次动作是打开wifi,则相应的把按钮值变成‘关闭’字样,以便提示用户关闭wifi
              //alert(info);//反之则相反  
              info==true? alert('wifi已开启') : alert('wifi已关闭')
          }
          function errorCB(fs){//若出现意外无法正常打开/关闭wifi,则提示出错,并返回错误信息
              alert('打开wifi失败\n'+fs.code);
          }
      }else{
        this.jumpSet();
      }
    },
    //设置网络
    toggleInternet:function(){
      if (cordovaFlag)
      if(this.initialize()=='android'){
        cordova.plugins.hotspot.openSetting();
      }else{
        this.jumpSet();
      }
    },
    //budly崩溃捕获和灰度更新 
    //崩溃捕获需在budly管理平台查看
    //budly初始化
    budlyInit:function(onSuccess,onError){
      if (cordovaFlag)
      cordova.exec(onSuccess,onError,'Bugly','init')
    },
    //budly检查是否有新版本(budly初始化后)
    budly:function(onSuccess,onError){
      if (cordovaFlag)
      // cordova.exec(onSuccess,onError,'Bugly','checkUpgrade')    //检查灰度更新
      Bugly.checkUpgrade(onSuccess,onError)
    },
    //获取系统默认语言 
    globalization:function(callback){
      if (cordovaFlag)
      navigator.globalization.getPreferredLanguage(function(local){
        callback && callback(local.value);
      },function() {
        alert('Error getting locale\n');
      });
    },
    //友盟统计和分享(本地)
    //Shareinfo里type:, 0 企业微信 1 qq 2 微信好友 3 微信朋友圈  4 微博 5 钉钉 6支付宝 
    umeng:function(onSuccess,onError,shareinfo){
      cordova.exec(onSuccess, onError, "Umeng","shareUrl", [shareinfo]);
    },
    //屏幕亮度调节
    brightness:function(onSuccess,onError,value){
      cordova.plugins.brightness.setBrightness(value, onSuccess, onError);
    },
    //截屏
    screenshot:function(callback){
      cordova.exec(onSuccess, onError,"Screenshot", "saveScreenshot", ['jpg', 100, 'pho']);
      function onSuccess(data){
        alert('success:'+data.filePath);
        callback && callback(data.filePath);
      };
      function onError(res){
        alert('error:'+res)
      }
    },
    //屏幕录制  开始  
    startRecord:function(filePath,onSuccess,onError){
      //filePath 文件名称
      var options={
        isAudio:true,     //如果为true,则插件使用MediaRecorder录制音频和视频
        width:720,     //以像素为单位的宽度来记录屏幕
        height:1280,     //以像 素为单位记录屏幕的高度
        bitRate:6000000,     //视频的比特率
        dpi:1     //视频的dpi
      }
      cordova.exec(onSuccess, onError, "ScreenRecord", "startRecord", [options, filePath]);
    },
    //屏幕录制  停止
    stopRecord:function(onSuccess,onError){
      cordova.exec(onSuccess, onError, "ScreenRecord", "stopRecord", []);
    },
    //指纹识别 
    //android
    //检查服务是否可用  如果指纹认证在设备上可用,则返回可解析的Promise。
    isAvailable:function(){
      FingerprintAuth.isAvailable(isAvailableSuccess, isAvailableError);
      function isAvailableSuccess(result) {
        alert("FingerprintAuth available: " + JSON.stringify(result));
        if (result.isAvailable) {
          var encryptConfig = {}; // See config object for required parameters
          FingerprintAuth.encrypt(encryptConfig, encryptSuccessCallback, encryptErrorCallback);
        }
      }
      
      function isAvailableError(message) {
        alert("isAvailableError(): " + message);
      }
    },
    // 打开原生对话框,使用设备硬件指纹扫描器对设备注册的指纹进行身份验证。
    encrypt:function(){
      var encryptConfig = {
        clientId: "myAppName",
        username: "currentUser",
        password: "currentUserPassword"
      }; 
      FingerprintAuth.encrypt(encryptConfig, successCallback, errorCallback);
       
      function successCallback(result) {
        alert('指纹验证通过')
        // alert("successCallback(): " + JSON.stringify(result));
        if (result.withFingerprint) {
          // alert("Successfully encrypted credentials.");
          // alert("Encrypted credentials: " + result.token);  
        } else if (result.withBackup) {
          alert("Authenticated with backup password");
        }
      }
       
      function errorCallback(error) {
        if (error === FingerprintAuth.ERRORS.FINGERPRINT_CANCELLED) {
          alert("FingerprintAuth Dialog Cancelled!");
        } else {
          alert("FingerprintAuth Error: " + error);
        }
      }
    },
    //打开原生对话框,使用设备硬件指纹扫描器对设备注册的指纹进行身份验证
    decrypt:function(){
      var decryptConfig = {
        clientId: "myAppName",
        username: "currentUser",
        token: "base64encodedUserCredentials"
      };
      FingerprintAuth.decrypt(decryptConfig, successCallback, errorCallback);
      function successCallback(result) {
        alert("successCallback(): " + JSON.stringify(result));
        if (result.withFingerprint) {
          alert("Successful biometric authentication.");
          if (result.password) {
            alert("Successfully decrypted credential token.");
            alert("password: " + result.password);  
          }
        } else if (result.withBackup) {
          alert("Authenticated with backup password");
        }
      }
      function errorCallback(error) {
        if (error === FingerprintAuth.ERRORS.FINGERPRINT_CANCELLED) {
          alert("FingerprintAuth Dialog Cancelled!");
        } else {
          alert("FingerprintAuth Error: " + error);
        }
      }
    },
    //删除用于加密和解密的密码  如果密码被成功删除,则返回一个可解析的Promise
    deletes:function(){
      FingerprintAuth.delete({
        clientId: "myAppName",
        username: "usernameToDelete"
      }, successCallback, errorCallback);
      function successCallback(result) {
        alert("Successfully deleted cipher: " + JSON.stringify(result));
      }
      function errorCallback(error) {
        alert(error);
      }
    },
    //用于在显示指纹认证对话框时将其解除
    dismiss:function(){
      FingerprintAuth.dismiss(successCallback, errorCallback); 
      function successCallback(result) {
        alert("Successfully dismissed FingerprintAuth dialog: " + JSON.stringify(result));
      }     
      function errorCallback(error) {
        alert(error);
      }
    },
    //ios指纹验证
    iosisAvailable:function(){
      window.plugins.touchid.isAvailable(
        function(type) {alert(type)}, // type returned to success callback: 'face' on iPhone X, 'touch' on other devices
        function(msg) {alert('not available, message: ' + msg)} // error handler: no TouchID available
      );
    },
    verifyFingerprint:function(){
      window.plugins.touchid.verifyFingerprint(
        'Scan your fingerprint please', // this will be shown in the native scanner popup
         function(msg) {alert('ok: ' + msg)}, // success handler: fingerprint accepted
         function(msg) {alert('not ok: ' + JSON.stringify(msg))} // error handler with errorcode and localised reason
      );
    },
    verifyFingerprintWithCustomPasswordFallback:function(){
      window.plugins.touchid.verifyFingerprintWithCustomPasswordFallback(
        'Scan your fingerprint please', // this will be shown in the native scanner popup
         function(msg) {alert('ok: ' + msg)}, // success handler: fingerprint accepted
         function(msg) {alert('not ok: ' + JSON.stringify(msg))} // error handler with errorcode and localised reason
      );
    },
    verifyFingerprintWithCustomPasswordFallbackAndEnterPasswordLabel:function(){
      window.plugins.touchid.verifyFingerprintWithCustomPasswordFallbackAndEnterPasswordLabel(
        'Scan your fingerprint please', // this will be shown in the native scanner popup
        'Enter PIN', // this will become the 'Enter password' button label
         function(msg) {alert('ok: ' + msg)}, // success handler: fingerprint accepted
         function(msg) {alert('not ok: ' + JSON.stringify(msg))} // error handler with errorcode and localised reason
      );
    },
    //录音
	  judgeRecorder:function(successCallback) {
      cordova.exec(successCallback, null, "AudioRecorderAPI", "requestPermission", []);
    },
    //开始录音
    recorderRecord:function(successCallback, errorCallback) {
      cordova.exec(successCallback, errorCallback, "AudioRecorderAPI", "record", [0]);
    },
    //停止录音
    recorderStop:function(successCallback, errorCallback) {
      cordova.exec(successCallback, errorCallback, "AudioRecorderAPI", "stop", []);
    },
    //百度语音识别 
    // 开启语音识别
    startSpeechRecognize:function(){
      // cordova.exec(successCallback, errorCallback, "bdasr", "startSpeechRecognize", [arg0]);
      cordova.plugins.bdasr.startSpeechRecognize();
    },
    // 语音识别事件监听
    addEventListenerRecognize:function(successCallback, errorCallback){
      cordova.exec(successCallback, errorCallback, "bdasr", "addEventListener");
    },
    // 主动结束语音识别
    closeSpeechRecognize:function(){
      // cordova.exec(successCallback, errorCallback, "bdasr", "closeSpeechRecognize", [arg0]);
      cordova.plugins.bdasr.closeSpeechRecognize();
    },
    // 主动取消语音识别
    cancelSpeechRecognize:function(){
      // cordova.exec(successCallback, errorCallback, "bdasr", "cancelSpeechRecognize", [arg0]);
      cordova.plugins.bdasr.cancelSpeechRecognize();
    },
    //由于ios无法设置网络、wifi、蓝牙操作,只能跳到设置页去
    jumpSet:function(successCallback, errorCallback){
      cordova.exec(successCallback, errorCallback, "JumpSetting", "jumpSetting");
    },
    // 文件存储和读取
    //需要在config.xml文件中配置<preference name="AndroidPersistentFileLocation" value="Compatibility" />
    //directoryName文件夹名称 fileName文件名
    /*
	 * 打开或创建文件夹,创建文件并写入内容
	 * Android:sdcard/xbrother/目录
	 * IOS:cdvfile://localhost/persistent/xbrother/目录
	 * 文件目录存在则打开,不存在则创建
	 * */
    createAndWriteFile:function(directoryName,callback){
      var fileName=document.getElementById("file").files[0].name; //DOM对象id为file
      if(!directoryName) directoryName='xbrother';
      if(document.getElementById("file").files[0]==undefined){
        alert('请先选择文件');
        return;
      };
      window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
        alert('打开的文件系统: ' + fs.name);

        fs.root.getDirectory(directoryName, {create: true}, function (dirEntry) {
          dirEntry.getFile(fileName, {create: true, exclusive: false}, function (fileEntry) {
            // alert(fileEntry.nativeURL)
            //files.fileUrl=fileEntry.nativeURL;    //文件路径
            //文件内容
            //var dataObj = new Blob('32323232', {type: 'text/plain'});
            var dataObj=document.getElementById("file").files[0];   //传入的文件
            //写入文件
            app.writeFile(fileEntry,dataObj,callback);
          },this.onErrorCreateFile);
        },this.onErrorGetDir);
      },this.onErrorLoadFs);
        
    },
    //将内容数据写入到文件中
    writeFile:function(fileEntry, dataObj,callback){
      //创建一个写入对象
      fileEntry.createWriter(function (fileWriter) {
        //文件写入成功
        fileWriter.onwriteend = function () {
          alert("Successful file write...");
          callback && callback(files)
        };
    
        //文件写入失败
        fileWriter.onerror = function (e) {
          alert("Failed file write: " + e.toString())
        };
    
        //写入文件
        fileWriter.write(dataObj);
      });
    },
    /* 依次打开指定目录文件夹,读取文件内容
    * Android:sdcard/xbrother/assets/task.json
    * IOS:cdvfile://localhost/persistent/xbrother/assets/task.json
    * 目录和文件存在则打开,不存在则退出
    * */
    getAndReadFile:function(directoryName,callback){
      var array=[];
     if(!directoryName) directoryName='xbrother';
      window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
  			// alert('打开的文件系统: ' + fs.name);
        fs.root.getDirectory(directoryName, {create: false}, function (dirEntry) {
          //读取当前文件夹下的所有文件
          dirEntry.createReader().readEntries(  //如果 entry 已经是 DirectoryEntry 可以直接从这步开始
            function(entry_array){
                // alert(JSON.stringify(entry_array));
                for(var index in entry_array){
                    array.push({name:entry_array[index].name,url:entry_array[index].toURL()})
                    // alert(entry_array[index].toURL());  //native file
                    // alert(entry_array[index].toInternalURL());  //cdvfile
                };
                callback && callback(array);
            },
            function (file_error) {
                alert("遍历错误:" + file_error);
            }
          )
          //读取指定文件
          // dirEntry.getFile(fileName, {create: false, exclusive: false}, function (fileEntry) {
          //   // alert("是否是个文件?" + fileEntry.isFile.toString());
          //   app.readFile(fileEntry);
          // }, app.onErrorCreateFile);
        },function(){
          // alert('请先写入文件')
        });
      }, app.onErrorLoadFs);
    },
    //读取文件
    readFile:function(fileEntry){
      fileEntry.file(function (file) {
        var reader = new FileReader();
        reader.onloadend = function () {
          document.getElementById('iframes').src=fileEntry.toURL();
        };
        reader.readAsText(file);
      }, app.onErrorReadFile);
    },
    onErrorCreateFile:function(){
      alert("文件创建失败!")
    },
    onErrorGetDir:function(){
      alert("文件夹创建失败!")
    },
    onErrorLoadFs:function(){
      alert("文件系统加载失败!")
    },
    //读取文件失败响应
    onErrorReadFile:function() {
    //		console.log("文件读取失败!");
      alert("文件读取失败!");
    },
    //人脸识别
    facesDetect:function(successCallback,errorCallback,token){
      cordova.exec(successCallback, errorCallback, "FaceID", "facesDetect",[token]);
    },
    //身份证识别
    IDDetect:function(successCallback,errorCallback,IDDetectInfo){
      cordova.exec(successCallback, errorCallback, "FaceID", "IDDetect",[IDDetectInfo]);
    }
  }
})();
document.addEventListener("deviceready", function (){
  window.JPush.init();
  window.JPush.getUserNotificationSettings(function(data){
    data==0? alert('请先开启系统通知权限') : '';
  })
},false);


 

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值