Skip to content

Cordova 开发日记 04:常用插件与使用

常用插件推荐

1.cordova-plugin-camera 相机拍照

安装:

sh
cordova plugin add cordova-plugin-camera

获取照片:

js
camera.getPicture(successCallback, errorCallback, options);

关于 options 的详细说明: http://cordova.apache.org/docs/en/latest/reference/cordova-plugin-camera/index.html#module_camera.CameraOptions

2.cordova-plugin-device 检查当前操作系统和设备情况

安装:

sh
cordova plugin add cordova-plugin-device

属性:

sh
device.cordova
device.model
device.platform
device.uuid
device.version
device.manufacturer
device.isVirtual
device.serial

3. cordova-plugin-file 文件

安装:

sh
cordova plugin add cordova-plugin-file

创建一个永久的文件:

js
window.requestFileSystem(
  LocalFileSystem.PERSISTENT,
  0,
  function (fs) {
    console.log("file system open: " + fs.name);
    fs.root.getFile(
      "newPersistentFile.txt",
      { create: true, exclusive: false },
      function (fileEntry) {
        console.log("fileEntry is file?" + fileEntry.isFile.toString());
        // fileEntry.name == 'someFile.txt'
        // fileEntry.fullPath == '/someFile.txt'
        writeFile(fileEntry, null);
      },
      onErrorCreateFile
    );
  },
  onErrorLoadFs
);

创建一个临时文件:

js
window.requestFileSystem(
  window.TEMPORARY,
  5 * 1024 * 1024,
  function (fs) {
    console.log("file system open: " + fs.name);
    createFile(fs.root, "newTempFile.txt", false);
  },
  onErrorLoadFs
);

function createFile(dirEntry, fileName, isAppend) {
  // Creates a new file or returns the file if it already exists.
  dirEntry.getFile(
    fileName,
    { create: true, exclusive: false },
    function (fileEntry) {
      writeFile(fileEntry, null, isAppend);
    },
    onErrorCreateFile
  );
}

写文件:

js
function writeFile(fileEntry, dataObj) {
  // Create a FileWriter object for our FileEntry (log.txt).
  fileEntry.createWriter(function (fileWriter) {
    fileWriter.onwriteend = function () {
      console.log("Successful file read...");
      readFile(fileEntry);
    };

    fileWriter.onerror = function (e) {
      console.log("Failed file read: " + e.toString());
    };

    // If data object is not passed in,
    // create a new Blob instead.
    if (!dataObj) {
      dataObj = new Blob(["some file data"], { type: "text/plain" });
    }

    fileWriter.write(dataObj);
  });
}

读文件:

js
function readFile(fileEntry) {
  fileEntry.file(function (file) {
    var reader = new FileReader();

    reader.onloadend = function () {
      console.log("Successful file read: " + this.result);
      displayFileData(fileEntry.fullPath + ": " + this.result);
    };

    reader.readAsText(file);
  }, onErrorReadFile);
}

更多使用方式: http://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/index.html#append-a-file-using-alternative-methods-

4.cordova-plugin-file-transfer 文件上传和下载

安装:

sh
cordova plugin add cordova-plugin-file-transfer

例子:

js
// !! Assumes variable fileURL contains a valid URL to a text file on the device,
//    for example, cdvfile://localhost/persistent/path/to/file.txt

var win = function (r) {
  console.log("Code = " + r.responseCode);
  console.log("Response = " + r.response);
  console.log("Sent = " + r.bytesSent);
};

var fail = function (error) {
  alert("An error has occurred: Code = " + error.code);
  console.log("upload error source " + error.source);
  console.log("upload error target " + error.target);
};

var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURL.substr(fileURL.lastIndexOf("/") + 1);
options.mimeType = "text/plain";

var params = {};
params.value1 = "test";
params.value2 = "param";

options.params = params;

var ft = new FileTransfer();
ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options);

自定义 headers 和 onprocess:

js
function win(r) {
  console.log("Code = " + r.responseCode);
  console.log("Response = " + r.response);
  console.log("Sent = " + r.bytesSent);
}

function fail(error) {
  alert("An error has occurred: Code = " + error.code);
  console.log("upload error source " + error.source);
  console.log("upload error target " + error.target);
}

var uri = encodeURI("http://some.server.com/upload.php");

var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURL.substr(fileURL.lastIndexOf("/") + 1);
options.mimeType = "text/plain";

var headers = { headerParam: "headerValue" };

options.headers = headers;

var ft = new FileTransfer();
ft.onprogress = function (progressEvent) {
  if (progressEvent.lengthComputable) {
    loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total);
  } else {
    loadingStatus.increment();
  }
};
ft.upload(fileURL, uri, win, fail, options);

下载文件:

js
// !! Assumes variable fileURL contains a valid URL to a path on the device,
//    for example, cdvfile://localhost/persistent/path/to/downloads/

var fileTransfer = new FileTransfer();
var uri = encodeURI("http://some.server.com/download.php");

fileTransfer.download(
  uri,
  fileURL,
  function (entry) {
    console.log("download complete: " + entry.toURL());
  },
  function (error) {
    console.log("download error source " + error.source);
    console.log("download error target " + error.target);
    console.log("upload error code" + error.code);
  },
  false,
  {
    headers: {
      Authorization: "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==",
    },
  }
);

终止传输:

js
// !! Assumes variable fileURL contains a valid URL to a text file on the device,
//    for example, cdvfile://localhost/persistent/path/to/file.txt

var win = function (r) {
  console.log("Should not be called.");
};

var fail = function (error) {
  // error.code == FileTransferError.ABORT_ERR
  alert("An error has occurred: Code = " + error.code);
  console.log("upload error source " + error.source);
  console.log("upload error target " + error.target);
};

var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = "myphoto.jpg";
options.mimeType = "image/jpeg";

var ft = new FileTransfer();
ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options);
ft.abort();

更多使用方式: http://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file-transfer/index.html#installation

5.cordova-plugin-geolocation 获取经纬度

安装:

sh
cordova plugin add cordova-plugin-geolocation

例子:

js
// onSuccess Callback
// This method accepts a Position object, which contains the
// current GPS coordinates
//
var onSuccess = function (position) {
  alert(
    "Latitude: " +
      position.coords.latitude +
      "\n" +
      "Longitude: " +
      position.coords.longitude +
      "\n" +
      "Altitude: " +
      position.coords.altitude +
      "\n" +
      "Accuracy: " +
      position.coords.accuracy +
      "\n" +
      "Altitude Accuracy: " +
      position.coords.altitudeAccuracy +
      "\n" +
      "Heading: " +
      position.coords.heading +
      "\n" +
      "Speed: " +
      position.coords.speed +
      "\n" +
      "Timestamp: " +
      position.timestamp +
      "\n"
  );
};

// onError Callback receives a PositionError object
//
function onError(error) {
  alert("code: " + error.code + "\n" + "message: " + error.message + "\n");
}

navigator.geolocation.getCurrentPosition(onSuccess, onError);

6.cordova-plugin-inappbrowser 浏览器,用于打开文件

安装:

sh
cordova plugin add cordova-plugin-inappbrowser

使用:

js
var ref = cordova.InAppBrowser.open(url, target, options);

ref 是对目标 window 的引用

更多用法: http://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/index.html#installation

7.cordova-plugin-splashscreen 显示 App 启动时的过渡页面

安装:

sh
cordova plugin add cordova-plugin-splashscreen

资源目录结构:

sh
projectRoot
    hooks
    platforms
    plugins
    www
        css
        img
        js
    res
        screen
            android
            ios
            windows

配置文件:

xml
<platform name="android">
    <!-- you can use any density that exists in the Android project -->
    <splash src="res/screen/android/splash-land-hdpi.png" density="land-hdpi"/>
    <splash src="res/screen/android/splash-land-ldpi.png" density="land-ldpi"/>
    <splash src="res/screen/android/splash-land-mdpi.png" density="land-mdpi"/>
    <splash src="res/screen/android/splash-land-xhdpi.png" density="land-xhdpi"/>

    <splash src="res/screen/android/splash-port-hdpi.png" density="port-hdpi"/>
    <splash src="res/screen/android/splash-port-ldpi.png" density="port-ldpi"/>
    <splash src="res/screen/android/splash-port-mdpi.png" density="port-mdpi"/>
    <splash src="res/screen/android/splash-port-xhdpi.png" density="port-xhdpi"/>
</platform>

<platform name="ios">
    <!-- images are determined by width and height. The following are supported -->
    <splash src="res/screen/ios/Default~iphone.png" width="320" height="480"/>
    <splash src="res/screen/ios/Default@2x~iphone.png" width="640" height="960"/>
    <splash src="res/screen/ios/Default-Portrait~ipad.png" width="768" height="1024"/>
    <splash src="res/screen/ios/Default-Portrait@2x~ipad.png" width="1536" height="2048"/>
    <splash src="res/screen/ios/Default-Landscape~ipad.png" width="1024" height="768"/>
    <splash src="res/screen/ios/Default-Landscape@2x~ipad.png" width="2048" height="1536"/>
    <splash src="res/screen/ios/Default-568h@2x~iphone.png" width="640" height="1136"/>
    <splash src="res/screen/ios/Default-667h.png" width="750" height="1334"/>
    <splash src="res/screen/ios/Default-736h.png" width="1242" height="2208"/>
    <splash src="res/screen/ios/Default-Landscape-736h.png" width="2208" height="1242"/>
</platform>
<preference name="SplashScreenDelay" value="10000" />

控制显示: 是否自动隐藏:

xml
<preference name="AutoHideSplashScreen" value="true" />

延迟:

xml
<preference name="SplashScreenDelay" value="3000" />

禁用:

xml
<preference name="SplashScreenDelay" value="0"/>
<preference name="FadeSplashScreenDuration" value="0"/>

淡出:

xml
<preference name="FadeSplashScreen" value="false"/>

淡出时间:

xml
<preference name="FadeSplashScreenDuration" value="750"/>

手动操作:

js
navigator.splashscreen.show();
window.setTimeout(function () {
  navigator.splashscreen.hide();
}, splashDuration - fadeDuration);

圈圈

xml
<preference name="ShowSplashScreenSpinner" value="false"/>

8.cordova-plugin-appversion 获取版本

sh
cordova plugin add cordova-plugin-appversion

使用:

js
console.log(AppVersion.version); // e.g. "1.2.3"
console.log(AppVersion.build); // e.g. 1234

10.phonegap-plugin-barcodescanner 条码和二维码扫描

安装:

sh
cordova plugin add phonegap-plugin-barcodescanner

使用:

js
cordova.plugins.barcodeScanner.scan(
  function (result) {
    //  console.log("We got a barcode\n" +
    //        "Result: " + result.text + "\n" +
    //        "Format: " + result.format + "\n" +
    //        "Cancelled: " + result.cancelled);
    let r_array = result.text.split(",");
    let obj = {};
    for (let i = 0; i < r_array.length; i++) {
      let o = r_array[i].split(":");
      obj[o[0]] = o[1];
    }
    //  alert(JSON.stringify(obj));
    let param = {
      type: obj["类型"],
      id: obj["ID"],
    };
    sessionStorage.setItem("tunnel", JSON.stringify(obj));
    location.hash = "/qrcode_page";
  },
  function (error) {
    alert("Scanning failed: " + error);
  },
  {
    // "preferFrontCamera" : true, // iOS and Android
    showFlipCameraButton: true, // iOS and Android
    prompt: "Place a barcode inside the scan area", // supported on Android only
    formats: "QR_CODE,PDF_417", // default: all but PDF_417 and RSS_EXPANDED
    orientation: "landscape", // Android only (portrait|landscape), default unset so it rotates with the device
  }
);

11.com.sarriaroman.PhotoViewer 图片预览

安装:

sh
cordova plugin add com-sarriaroman-photoviewer

使用:

js
PhotoViewer.show("http://my_site.com/my_image.jpg", "Optional Title");

12.cordova-plugin-datepicker 日期选择

安装:

sh
cordova plugin add cordova-plugin-datepicker

使用:

js
var options = {
  date: new Date(),
  mode: "date",
};

function onSuccess(date) {
  alert("Selected date: " + date);
}

function onError(error) {
  // Android only
  alert("Error: " + error);
}

datePicker.show(options, onSuccess, onError);

13.cordova-plugin-crosswalk-webview 第三方 webview

安装:

sh
cordova plugin add cordova-plugin-crosswalk-webview
cordova build android

输出路径:

sh
/path/to/hello/platforms/android/build/outputs/apk/hello-x86-debug.apk
/path/to/hello/platforms/android/build/outputs/apk/hello-armv7-debug.apk

详细说明: https://www.npmjs.com/package/cordova-plugin-crosswalk-webview

14.cordova-plugin-fastrde-downloader 多文件下载器,可以解压 zip

安装:

sh
cordova plugin add https://github.com/fastrde/phonegap-downloader.git

使用:

js
// 初始化
downloader.init({ folder: "yourPersistantAppFolder", unzip: true });
// 单文件下载
downloader.get("http://yourhost.de/some.zip");
// 多文件下载
downloader.getMultipleFiles([
  { url: "http://yourhost.de/some1.zip" },
  { url: "http://yourhost.de/some2.zip" },
  { url: "http://yourhost.de/some3.zip" },
]);
// 终止
downloader.abort();

// 事件
document.addEventListener(eventName, function (event) {
  var data = event.data;
});
sh
eventNames:
DOWNLOADER_initialized        data:none
DOWNLOADER_gotFileSystem      data:[cordova.fileSystem fileSystem]
DOWNLOADER_gotFolder          data:[cordova.fileEntry folder]
DOWNLOADER_error              data:[object error]
DOWNLOADER_noWifiConnection   data:none
DOWNLOADER_downloadSuccess    data:[cordova.fileEntry entry]
DOWNLOADER_downloadError      data:[object error]
DOWNLOADER_downloadProgress   data:[number percentage, string fileName]
DOWNLOADER_unzipSuccess       data:[string fileName]
DOWNLOADER_unzipError         data:[string fileName]
DOWNLOADER_unzipProgress      data:[number percentage, string fileName]
DOWNLOADER_fileRemoved        data:[cordova.fileEntry entry]
DOWNLOADER_fileRemoveError    data:[cordova.fileEntry entry]
DOWNLOADER_getFileError       data:[object error]
DOWNLOADER_fileCheckSuccess   data:[string md5sum, string fileName]
DOWNLOADER_fileCheckFailed    data:[string calculatedMd5sum, string md5, string fileName])
DOWNLOADER_fileCheckError     data:[object error]

15.cordova-sqlite-storage

安装:

sh
cordova plugin add cordova-sqlite-storage

打开数据库:

js
var db = window.sqlitePlugin.openDatabase({ name: "my.db", location: "default" }, successcb, errorcb);

旧版的兼容若出问题请看详细说明:

https://www.npmjs.com/package/cordova-sqlite-storage

js
//INSERT
db.executeSql(
  "INSERT INTO MyTable VALUES (?)",
  ["test-value"],
  function (resultSet) {
    console.log("resultSet.insertId: " + resultSet.insertId);
    console.log("resultSet.rowsAffected: " + resultSet.rowsAffected);
  },
  function (error) {
    console.log("SELECT error: " + error.message);
  }
);

//SELECT
db.executeSql(
  "SELECT LENGTH('tenletters') AS stringlength",
  [],
  function (resultSet) {
    console.log("got stringlength: " + resultSet.rows.item(0).stringlength);
  },
  function (error) {
    console.log("SELECT error: " + error.message);
  }
);

//batch
db.sqlBatch(
  [
    "DROP TABLE IF EXISTS MyTable",
    "CREATE TABLE MyTable (SampleColumn)",
    ["INSERT INTO MyTable VALUES (?)", ["test-value"]],
  ],
  function () {
    db.executeSql("SELECT * FROM MyTable", [], function (resultSet) {
      console.log("Sample column value: " + resultSet.rows.item(0).SampleColumn);
    });
  },
  function (error) {
    console.log("Populate table error: " + error.message);
  }
);

16.cordova-plugin-nativestorage

安装:

sh
cordova plugin add cordova-plugin-nativestorage

使用:

js
NativeStorage.setItem("reference_to_value",<value>, <success-callback>, <error-callback>);
NativeStorage.getItem("reference_to_value",<success-callback>, <error-callback>);

Version 4.2 (core-1.3.4)