PhoneGap 外掛呼叫方法(以Camera為例)
阿新 • • 發佈:2019-02-17
PhoneGap 官方提供了各種外掛的API呼叫,我們就一Camera為例,總結一下PhoneGap外掛的呼叫。主要可以概括為以下幾步:
新建工程 -> 外掛下載 -> 工程編譯 -> 外掛匯入Eclipse -> 外掛呼叫
執行cmd,鍵入以下命令
phonegap create camera
cd camera
phonegap run android
然後開始下載外掛,鍵入以下命令
cd plugins
cordova plugin add cordova-plugin-camera
外掛下載完畢,新增Android平臺工程,鍵入以下命令
cordova platform add android
生成的Android工程進行編譯,這個過程可能會有點慢。Gradle有問題的可以參考:Gradle無法下載的解決辦法 。鍵入以下命令
cordova build
若編譯不通過,一般是環境變數、導包、引用庫的問題,不行就直接匯入吧,導不進去的話,去正常的Eclipse專案中拷貝.class和.project進去,就可以匯入了~~
匯入工程後,修改MainActivity
修改asset/www/index.html,直接替換成以下內容:package com.phonegap.helloworld; import android.os.Bundle; import org.apache.cordova.*; public class MainActivity extends CordovaActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); loadUrl("file:///android_asset/www/index.html"); } }
完成,run起來~~快試一試拍照吧~~~<!DOCTYPE html> <html> <head> <title>Capture Photo</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> var pictureSource; var destinationType; // 圖片返回格式 document.addEventListener("deviceready",onDeviceReady,false); function onDeviceReady() { // 初始化 pictureSource=navigator.camera.PictureSourceType; destinationType=navigator.camera.DestinationType; } function onPhotoDataSuccess(imageData) { console.log(imageData); var smallImage = document.getElementById('smallImage'); smallImage.style.display = 'block'; smallImage.src = "data:image/jpeg;base64," + imageData; } function onPhotoURISuccess(imageURI) { console.log(imageURI); var largeImage = document.getElementById('largeImage'); largeImage.style.display = 'block'; largeImage.src = imageURI; } function capturePhoto() { // 不可編輯頁面 navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50, destinationType: destinationType.DATA_URL }); } function capturePhotoEdit() { // 可編輯圖片 navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,destinationType: destinationType.DATA_URL }); } function getPhoto(source) { // 相簿 navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50, destinationType: destinationType.FILE_URI,sourceType: source }); } function onFail(message) { alert('Failed because: ' + message); } </script> </head> <body> <button onclick="capturePhoto();">拍照</button> <br> <button onclick="capturePhotoEdit();">可編輯拍照</button> <br> <button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">相簿方式一(PHOTOLIBRARY)</button><br> <button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">相簿方式二(SAVEDPHOTOALBUM)</button><br> <img style="display:none;width:60px;height:60px;" id="smallImage" src="" /> <img style="display:none;" id="largeImage" src="" /> </body> </html>
最後,附上Demo的下載地址~~PhoneGap Camera外掛呼叫 Demo下載