生成Cordova项目,给Cordova加插件

来源:互联网 发布:分期乐软件靠谱吗 编辑:程序博客网 时间:2024/06/16 15:15

安装Cordova CLI
Cordova命令行工具是由npm包分发的。

安装cordova命令行工具,通过下面步骤:
1.下载和安装Node.js。安装完成后你可以在命令行中使用node 和 npm 。

2.(可选)下载和安装git client, 如果你没有。安装成功后,你可以在命令行中使用git。 这个命令行使用下载git仓库中的资源。

3.安装cordova 模块使用Nodejs的npm工具。cordova模块会被npm工具自动下载
在OS X和Linux上:

$ sudo npm install -g cordova //这里要下载安装cordova,在命令行要等一会

之后我们在命令行输入:

amelon:~ amelon$ cordova  

如果显示的是这种,表明你安装成功了:

Global Commands    create ............................. Create a project    help ............................... Get help for a command    telemetry .......................... Turn telemetry collection on or offProject Commands    info ............................... Generate project information    requirements ....................... Checks and print out all the requirements                                            for platforms specified    platform ........................... Manage project platforms    plugin ............................. Manage project plugins    prepare ............................ Copy files into platform(s) for building    compile ............................ Build platform(s)    clean .............................. Cleanup project from build artifacts    run ................................ Run project                                            (including prepare && compile)    serve .............................. Run project with a local webserver                                            (including prepare)

查看当前cordova安装版本:

amelon:~ amelon$ cordova --v6.5.0 //版本号

生成一个cordova 项目:

amelon:~ amelon$ cordova create helloworld user.example.cordovaCreating a new cordova project.

找到生成的文件,打开目录为:

helloworld/|____config.xml|____hooks| |____README.md|____platforms|____plugins|____www| |____css| | |____index.css| |____img| | |____logo.png| |____index.html| |____js| | |____index.js

加入android平台(ios,browser…)

amelon:~ amelon$ cd helloworldamelon:helloworld amelon$ cordova platform add android --savaAdding android project...Creating Cordova project for the Android platform:    Path: platforms/android    Package: user.example.cordova    Name: HelloCordova    Activity: MainActivity    Android target: android-25Subproject Path: CordovaLibAndroid project created with cordova-android@6.1.2Discovered plugin "cordova-plugin-whitelist" in config.xml. Adding it to the projectFetching plugin "cordova-plugin-whitelist@1" via npmInstalling "cordova-plugin-whitelist" for android               This plugin is only applicable for versions of cordova-android greater than 4.0. If you have a previous platform version, you do *not* need this plugin since the whitelist will be built in.

打开platform就会看到这样的目录:

/platform|android|__android.json|--AndroidManifest.xml|--assets|__build.gradle|--cordova|--CordovaLib|--libs|--platform_www|__project.properties|--res|__settings.gradle|--src|platforms.json

在我们添加Andorid支持平台的时候,Cordova会为我们添加一个默认插件,也就是上面信息中所打印的cordova-plugin-whitelist并且自动在config.xml文件中已经帮我们配置
自己加一个调用照相机的插件:

amelon:helloworld amelon$ cd pluginsamelondeMacBook-Pro:plugins amelon$ cordova plugin add cordova-plugin-cameraFetching plugin "cordova-plugin-camera" via npmInstalling "cordova-plugin-camera" for androidFetching plugin "cordova-plugin-compat" via npmInstalling "cordova-plugin-compat" for androidSubproject Path: CordovaLib

打开plugins目录:

/platform|android.json|__cordova-plugin-camera|--cordova-plugin-compat|--cordova-plugin-whitelist|fetch.json|www

编译并运行:

amelon:plugins amelon$ cordova buildANDROID_HOME=/Users/amelon/Library/Android/sdkJAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/HomeSubproject Path: CordovaLibStarting a new Gradle Daemon for this build (subsequent builds will be faster).Incremental java compilation is an incubating feature.:preBuild UP-TO-DATE:preDebugBuild UP-TO-DATE:checkDebugManifest:CordovaLib:preBuild UP-TO-DATE:CordovaLib:preDebugBuild UP-TO-DATE:CordovaLib:checkDebugManifest:CordovaLib:prepareDebugDependencies:CordovaLib:compileDebugAidl.......................................................:compileDebugShaders UP-TO-DATE:generateDebugAssets UP-TO-DATE:mergeDebugAssets UP-TO-DATE:transformClassesWithDexForDebug UP-TO-DATE:mergeDebugJniLibFolders UP-TO-DATE:transformNative_libsWithMergeJniLibsForDebug UP-TO-DATE:processDebugJavaRes UP-TO-DATE:transformResourcesWithMergeJavaResForDebug UP-TO-DATE:validateSigningDebug:packageDebug UP-TO-DATE:assembleDebug UP-TO-DATE:cdvBuildDebug UP-TO-DATEBUILD SUCCESSFULTotal time: 1.512 secsBuilt the following apk(s):     /Users/amelon/helloworld/platforms/android/build/outputs/apk/android-debug.apk

把platform下的android项目导入androidstudio,运行一下:

//gradle的版本问题,在setting里设置对应的gradle版本即可Error:Failed to open zip file.Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)<a href="syncProject">Re-download dependencies and sync project (requires network)</a><a href="syncProject">Re-download dependencies and sync project (requires network)</a>

编译在运行一下项目:
运行界面
程序虽然能够正常跑起来,但这并没有什么用处,因为我们自己添加的照相机插件没有利用起来,于是我们写一份自己的html文件去覆盖这个界面文件。网上有现成的,觉得有点丑,自己动手改改,也可以自己写,清楚cordova的调用方法就可以了。

<!DOCTYPE html><html><head>    <title>调用照相机插件</title>    <style type="text/css">        button{            margin: 10px;            background-color: pink;            padding: 3px;            border: 0px;        }    </style>    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>    <script type="text/javascript" charset="utf-8">    var pictureSource;   // picture source    var destinationType; // sets the format of returned value    // Wait for device API libraries to load    //    document.addEventListener("deviceready",onDeviceReady,false);        // device APIs are available    //        function onDeviceReady() {                    pictureSource=navigator.camera.PictureSourceType;                   destinationType=navigator.camera.DestinationType;            }        // Called when a photo is successfully retrieved    //        function onPhotoDataSuccess(imageData) {        // Uncomment to view the base64-encoded image data      //        console.log(imageData);        // Get image handle      //        var smallImage = document.getElementById('smallImage');        // Unhide image elements      //        smallImage.style.display = 'block';        // Show the captured photo      // The in-line CSS rules are used to resize the image      //        smallImage.src = "data:image/jpeg;base64," + imageData;           }        // Called when a photo is successfully retrieved    //        function onPhotoURISuccess(imageURI) {        // Uncomment to view the image file URI      //        console.log(imageURI);        // Get image handle      //        var largeImage = document.getElementById('largeImage');        // Unhide image elements      //        largeImage.style.display = 'block';        // Show the captured photo      // The in-line CSS rules are used to resize the image      //        largeImage.src = imageURI;           }        // A button will call this function    //        function capturePhoto() {        // Take picture using device camera and retrieve image as base64-encoded string        navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,        destinationType: destinationType.DATA_URL });        }        // A button will call this function    //        function capturePhotoEdit() {        // Take picture using device camera, allow edit, and retrieve image as base64-encoded string        navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,        destinationType: destinationType.DATA_URL });        }        // A button will call this function    //        function getPhoto(source) {        // Retrieve image file location from specified source        navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,        destinationType: destinationType.FILE_URI,        sourceType: source });         }        // Called if something bad happens.    //        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);">获取相册</button><br><button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">另一种方法获取相册</button><br><img style="display:none;width:60px;height:60px;" id="smallImage" src="" /><img style="display:none;" id="largeImage" src="" /></body></html>

找到android/assets/www/index.html;打开注视全部,把粘贴的复制上去,在运行一次
这里写图片描述
点击实验一下,调用照相机和相册功能室完全没问题的,失败会走失败的方法,成功会拿到图片的地址,有的模拟器相机是有问题的,有问题的可以用真机测测

这篇久就写到这里吧,第二篇会详细讲讲插件相关的知识,有问题请留言拍砖,大家多多指教…

转载请表明地址:http://blog.csdn.net/zxyudia/article/details/61436289
代码下载地址:https://github.com/amelons/hello

0 0