生成Cordova项目,给Cordova加插件

安装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 off

Project 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 --v
6.5.0 //版本号

生成一个cordova 项目:

amelon:~ amelon$ cordova create helloworld user.example.cordova
Creating 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 helloworld
amelon:helloworld amelon$ cordova platform add android --sava
Adding android project...
Creating Cordova project for the Android platform:
    Path: platforms/android
    Package: user.example.cordova
    Name: HelloCordova
    Activity: MainActivity
    Android target: android-25
Subproject Path: CordovaLib
Android project created with cordova-android@6.1.2
Discovered plugin "cordova-plugin-whitelist" in config.xml. Adding it to the project
Fetching plugin "cordova-plugin-whitelist@1" via npm
Installing "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 plugins
amelondeMacBook-Pro:plugins amelon$ cordova plugin add cordova-plugin-camera
Fetching plugin "cordova-plugin-camera" via npm
Installing "cordova-plugin-camera" for android
Fetching plugin "cordova-plugin-compat" via npm
Installing "cordova-plugin-compat" for android
Subproject Path: CordovaLib

打开plugins目录:

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

编译并运行:

amelon:plugins amelon$ cordova build
ANDROID_HOME=/Users/amelon/Library/Android/sdk
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home
Subproject Path: CordovaLib
Starting 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-DATE

BUILD SUCCESSFUL

Total time: 1.512 secs
Built 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值