使用Ionic + Apache Cordova开发跨平台混合型的移动应用 - 非常好的手机开发初级文章!!!!!!

http://blog.csdn.net/zoutongyuan/article/details/41910903?utm_source=tuicool


JavaScript 写多了,要想真正提高js水平,研究其他js框架源码是不错的选择。Github上大部分都是js、css相关的项目,可以有目的性的 check out 下来,研读研读,还是非常收益的,跟随nb的人,也会慢慢变的nb。


场景:有一个朋友,他公司是做移动应用开发的,3个安卓开发人员,3个iOS,然后是Java 开发,美工 ,10多个人的公司,主要是以接项目为主,一个项目(电商、微信、聊天 类型的)大概在20万左右, 差不多1个半月 做完(代码质量能不能保证,不知道,不过我觉得开发是一件很严谨的事,要开发出高性能、高健壮性的程序,还是很难的),公司销售很给力,能谈下好几个项目。问题来了,要能同时进行好几个项目,就要招移动开发的人,如果有时没接到项目,那 ,又会闲着。如果有些 客户 要 做 wp ,黑莓的 ,那就做不来了。于是迫切 想 找一些跨平台的 开发技术 来 解决问题?


这个场景是真实的,不是 yy,那么我们来玩玩 Ionic ,Apache Cordova 这些技术,这样我们就有更深入的 理解了。

我做过 一些 安卓的小东西,ios 没玩过;我是一个  web技术 狂热者,很看好web技术;我认为那些Android 、ios 等等  将会慢慢 被 web 技术 取代,浏览器 作为跨平台的中间件,将会成为主流。do not mind


尊重原创,转载请注明出去:http://blog.csdn.NET/zoutongyuan/article/details/41910903


进入主题吧。

1、Ionic 是什么?

好吧,我们看 Ionic 能给我们提供什么?  一个样式库,你可以使用它 来 装饰你的 HTML 网页 ,看起来 想 移动程序的 界面,什么 header 、content、footer、grid、list。这貌似没什么 实质性的东西, sencha touch ,jq 都能提供 。

一个用AngularJS 写的 工具库,姑且叫它 组件库吧。Ionic的 grid 设计的比较合理,比 bootstrap的 更强大。

当然它 还包含 了angular-animate、angular-resource、angular-sanitize、angular-ui-router,适应移动平台的模块库。


2、Apache Cordova 是什么?

Apache Cordova 提供用 Javascript 访问 移动平台  的 API 。

其内部是用每个 平台下的  web view 组件,运行 程序,然后实现了 每个平台下的 一套 CordovaLib  供你写的程序调用,然后你就可以 调用 摄像头、磁盘等 重api。


接下来 动手玩玩。首先安装nodejs,和平台的 (ios || android)sdk,这里不在 累述 

1、先安装 cordova

npm install -g cordova

2、安装 Ionic

npm install -g ionic

3、创建项目

ionic start todo blank

4、配置平台

ionic platform add android

然后 在IDE中打开 项目:



www是主目录

index.html 是 主页面


刚才我们配置 平台的时候 ,工具帮我们做了一件事,创建 了一个 安卓 应用,

创建一个 CordovaApp 类,继承自 CordovaActivity , Activity 是 安卓的4大组件,表示可以看到 了一块窗口。

它做了一个 引导,就是loadUrl,这里不做过多的 介绍,有兴趣 我们以后深入研究,这里我们只是 发散性的引导。


现在,你就可以使用 ionic 和 Apache Cordova 提供的 api 来 开发 跨平台的应用了。


来改我们的index.html

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8">  
  5.     <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">  
  6.     <title></title>  
  7.   
  8.     <link href="lib/ionic/css/ionic.css" rel="stylesheet">  
  9.     <link href="css/style.css" rel="stylesheet">  
  10.   
  11.     <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above  
  12.     <link href="css/ionic.app.css" rel="stylesheet">  
  13.     -->  
  14.   
  15.     <!-- ionic/angularjs js -->  
  16.     <script src="lib/ionic/js/ionic.bundle.js"></script>  
  17.   
  18.     <!-- cordova script (this will be a 404 during development) -->  
  19.     <script src="cordova.js"></script>  
  20.   
  21.     <!-- your app's js -->  
  22.     <script src="js/app.js"></script>  
  23. </head>  
  24. <body ng-app="todoApp" ng-controller="TodoController" ng-cloak>  
  25.   
  26.     <ion-side-menus>  
  27.   
  28.         <!-- Center content -->  
  29.         <ion-side-menu-content>  
  30.             <ion-header-bar class="bar-dark">  
  31.                 <button class="button button-icon" ng-click="toggleProjects()">  
  32.                     <i class="icon ion-navicon"></i>  
  33.                 </button>  
  34.                 <h1 class="title">{{activeProject.title}}</h1>  
  35.                 <!-- New Task button-->  
  36.                 <button class="button button-icon" ng-click="newTask()">  
  37.                     <i class="icon ion-compose"></i>  
  38.                 </button>  
  39.             </ion-header-bar>  
  40.             <ion-content scroll="false">  
  41.                 <ion-list>  
  42.                     <ion-item ng-repeat="task in activeProject.tasks">  
  43.                         {{task.title}}  
  44.                     </ion-item>  
  45.                 </ion-list>  
  46.             </ion-content>  
  47.         </ion-side-menu-content>  
  48.   
  49.         <!-- Left menu -->  
  50.         <ion-side-menu side="left">  
  51.             <ion-header-bar class="bar-dark">  
  52.                 <h1 class="title">Projects</h1>  
  53.                 <button class="button button-icon ion-plus" ng-click="newProject()">  
  54.                 </button>  
  55.             </ion-header-bar>  
  56.             <ion-content scroll="false">  
  57.                 <ion-list>  
  58.                     <ion-item ng-repeat="project in projects" ng-click="selectProject(project, $index)" ng-class="{active: activeProject == project}">  
  59.                         {{project.title}}  
  60.                     </ion-item>  
  61.                 </ion-list>  
  62.             </ion-content>  
  63.         </ion-side-menu>  
  64.   
  65.     </ion-side-menus>  
  66.   
  67.     <script id="new-task.html" type="text/ng-template">  
  68.         <div class="modal">  
  69.   
  70.             <!-- Modal header bar -->  
  71.             <ion-header-bar class="bar-secondary">  
  72.                 <h1 class="title">New Task</h1>  
  73.                 <button class="button button-clear button-positive" ng-click="closeNewTask()">Cancel</button>  
  74.             </ion-header-bar>  
  75.   
  76.             <!-- Modal content area -->  
  77.             <ion-content>  
  78.   
  79.                 <form ng-submit="createTask(task)">  
  80.                     <div class="list">  
  81.                         <label class="item item-input">  
  82.                             <input type="text" placeholder="What do you need to do?" autofocus ng-model="task.title">  
  83.                         </label>  
  84.                     </div>  
  85.                     <div class="padding">  
  86.                         <button type="submit" class="button button-block button-positive">Create Task</button>  
  87.                     </div>  
  88.                 </form>  
  89.   
  90.             </ion-content>  
  91.         </div>  
  92.     </script>  
  93.   
  94. </body>  
  95. </html>  

js/app.js

  1. var todoApp = angular.module('todoApp', ['ionic']);  
  2.   
  3. todoApp.run(function ($ionicPlatform) {  
  4.     $ionicPlatform.ready(function () {  
  5.         if (window.cordova && window.cordova.plugins.Keyboard) {  
  6.             cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);  
  7.         }  
  8.         if (window.StatusBar) {  
  9.             StatusBar.styleDefault();  
  10.         }  
  11.     });  
  12. });  
  13.   
  14.   
  15. todoApp.controller('TodoController'function ($scope, $timeout, $ionicModal, Projects, $ionicSideMenuDelegate) {  
  16.   
  17.     // A utility function for creating a new project  
  18.     // with the given projectTitle  
  19.     var createProject = function (projectTitle) {  
  20.         var newProject = Projects.newProject(projectTitle);  
  21.         $scope.projects.push(newProject);  
  22.         Projects.save($scope.projects);  
  23.         $scope.selectProject(newProject, $scope.projects.length - 1);  
  24.     }  
  25.   
  26.   
  27.     // Load or initialize projects  
  28.     $scope.projects = Projects.all();  
  29.   
  30.     // Grab the last active, or the first project  
  31.     $scope.activeProject = $scope.projects[Projects.getLastActiveIndex()];  
  32.   
  33.     // Called to create a new project  
  34.     $scope.newProject = function () {  
  35.         var projectTitle = prompt('Project name');  
  36.         if (projectTitle) {  
  37.             createProject(projectTitle);  
  38.         }  
  39.     };  
  40.   
  41.     // Called to select the given project  
  42.     $scope.selectProject = function (project, index) {  
  43.         $scope.activeProject = project;  
  44.         Projects.setLastActiveIndex(index);  
  45.         $ionicSideMenuDelegate.toggleLeft(false);  
  46.     };  
  47.   
  48.     // Create our modal  
  49.     $ionicModal.fromTemplateUrl('new-task.html'function (modal) {  
  50.         $scope.taskModal = modal;  
  51.     }, {  
  52.         scope: $scope  
  53.     });  
  54.   
  55.     $scope.createTask = function (task) {  
  56.         if (!$scope.activeProject || !task) {  
  57.             return;  
  58.         }  
  59.         $scope.activeProject.tasks.push({  
  60.             title: task.title  
  61.         });  
  62.         $scope.taskModal.hide();  
  63.   
  64.         // Inefficient, but save all the projects  
  65.         Projects.save($scope.projects);  
  66.   
  67.         task.title = "";  
  68.     };  
  69.   
  70.     $scope.newTask = function () {  
  71.         $scope.taskModal.show();  
  72.     };  
  73.   
  74.     $scope.closeNewTask = function () {  
  75.         $scope.taskModal.hide();  
  76.     }  
  77.   
  78.     $scope.toggleProjects = function () {  
  79.         $ionicSideMenuDelegate.toggleLeft();  
  80.     };  
  81.   
  82.   
  83.     // Try to create the first project, make sure to defer  
  84.     // this by using $timeout so everything is initialized  
  85.     // properly  
  86.     $timeout(function () {  
  87.         if ($scope.projects.length == 0) {  
  88.             while (true) {  
  89.                 var projectTitle = prompt('Your first project title:');  
  90.                 if (projectTitle) {  
  91.                     createProject(projectTitle);  
  92.                     break;  
  93.                 }  
  94.             }  
  95.         }  
  96.     });  
  97.   
  98. });  
  99.   
  100.   
  101. todoApp.factory('Projects'function () {  
  102.     return {  
  103.         all: function () {  
  104.             var projectString = window.localStorage['projects'];  
  105.             if (projectString) {  
  106.                 return angular.fromJson(projectString);  
  107.             }  
  108.             return [];  
  109.         },  
  110.         save: function (projects) {  
  111.             window.localStorage['projects'] = angular.toJson(projects);  
  112.         },  
  113.         newProject: function (projectTitle) {  
  114.             // Add a new project  
  115.             return {  
  116.                 title: projectTitle,  
  117.                 tasks: []  
  118.             };  
  119.         },  
  120.         getLastActiveIndex: function () {  
  121.             return parseInt(window.localStorage['lastActiveProject']) || 0;  
  122.         },  
  123.         setLastActiveIndex: function (index) {  
  124.             window.localStorage['lastActiveProject'] = index;  
  125.         }  
  126.     }  
  127. })  

这个todo 我们没有用到 Apache Cordova 的api,所以,这个项目在浏览器中 也可以运行。

使用 

$ ionic serve


在我的小米3 中 看看。使用下面命令,你可能要安装好 驱动,

$ ionic run android


最后编译,

$ cordova build --release android

来评价这一些技术吧。

天下大势,合久必分,分久必合。

HTML5 + CSS3 + Javascript 最适合作为跨平台的技术栈,其开放 ,自由,每个人都可以 为这些技术的制定 ,发表意见 ,像 使用 svg 、canvas 、css 3动画 开发的游戏  ,已经在撼动 桌游, 手游 等 原生语言开发的 应用了,所以不仅仅是 应用。

而 Apache Cordova  只是 一个 过渡阶段的产物。对于 新技术的 出现 ,是值得鼓励的 。

让我们拭目以待,web 技术 明天的发展吧。


============================================================================

The following commands need to be ran:
1. npm install -g cordova
2. npm install -g ionic
3. ionic start <SampleProjectName> blank
4. ionic platform add [ios|android]
5. npm install -g ios-sim
6. npm install -g iso-deploy //Xcode must be installed into Mac OS before install the iso-deploy plugin due that it depends on Xcode tool
7. ionic serve
8. ionic run [ios|android|browser]

run <PLATFORM> [options] ......................  Run an Ionic project on a connected device
    [--livereload|-l]  ........................  Live reload app dev files from the device (beta)

    [--address]  ..............................  Use specific address (livereload req.)

    [--port|-p]  ..............................  Dev server HTTP port (8100 default, livereload req.)

    [--livereload-port|-r]  ...................  Live Reload port (35729 default, livereload req.)

    [--consolelogs|-c]  .......................  Print app console logs to Ionic CLI (livereload req.)

    [--serverlogs|-s]  ........................  Print dev server logs to Ionic CLI (livereload req.)

    [--debug|--release]  ......................  

    [--device|--emulator|--target=FOO] 

  • ionic run ios --device
  • ionic run ios --emulator
  • ionic run ios --target="iPhone-5s"
  • ionic run ios --target="iPhone-6"
  • ionic run ios --target="iPhone-6s"
  • ionic run ios --emulator --target="iPhone-6s" -l      

HaideMacBook-Pro:sampleApp2 liuhaidl$ ionic run ios --emulator --target="iPhone-6s" -l
Setup Live Reload

Multiple addresses available.
Please select which address to use by entering its number from the list below:
Note that the emulator/device must be able to access the given IP address
 1) 192.168.31.241 (en0)
 2) 9.197.226.42 (utun1)

com.ionicframework.sampleapp2937890: 17622

logPath: /Users/liuhaidl/Desktop/AMTools/SourceCodes/mobile/sampleApp2/platforms/ios/cordova/console.log

JS changed:   www/js/app.js
HTML changed: www/index.html


9. ionic emulate [ios|android]

============================================================================


Run Command: ionic run ios
Error: xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance
Solution: install Xcode tool from apple appstore

Run Command: ionic run ios
Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo.
Error: Error code 69 for command: xcodebuild with args: -xcconfig,/Users/liuhaidl/Desktop/AMTools/SourceCodes/mobile/sampleApp/platforms/ios/cordova/build-debug.xcconfig,-project,sampleApp.xcodeproj,ARCHS=i386,-target,sampleApp,-configuration,Debug,-sdk,iphonesimulator,build,VALID_ARCHS=i386,CONFIGURATION_BUILD_DIR=/Users/liuhaidl/Desktop/AMTools/SourceCodes/mobile/sampleApp/platforms/ios/build/emulator,SHARED_PRECOMPS_DIR=/Users/liuhaidl/Desktop/AMTools/SourceCodes/mobile/sampleApp/platforms/ios/build/sharedpch
Solution: sudo ionic run ios

HaideMacBook-Pro:emulator liuhaidl$ ls -lrt
total 1768
drwxr-xr-x   3 root  staff     102  2  7 21:39 include
-rw-r--r--   1 root  staff  904440  2  7 21:39 libCordova.a
drwxr-xr-x   3 root  staff     102  2  7 21:39 sampleApp.app.dSYM
drwxr-xr-x  46 root  staff    1564  2  7 21:39 sampleApp.app
HaideMacBook-Pro:emulator liuhaidl$ pwd
/Users/liuhaidl/Desktop/AMTools/SourceCodes/mobile/sampleApp/platforms/ios/build/emulator

Run Command: sudo ionic run ios

Error: No target specified for emulator. Deploying to iPhone-SE, 10.2 simulator
An error was encountered processing the command (domain=com.apple.CoreSimulator.SimError, code=163):
Unable to lookup in current state: Shutdown

Solution: The above issue has been fixed after I have created a new project using ionic command"ionic start <Create Project Name> blank"

Run Command: sudo ionic run ios

[....] Waiting up to 1 seconds for iOS device to be connected

[....] Found 19759d43b40f63cc098d334c85af3798646b59c7 (N51AP, iPhone 5s (GSM), iphoneos, arm64) a.k.a. 'Angela' iPhone' connected through USB.

Error: 2017-02-07 21:59:20.470 ios-deploy[11231:428045] [ !! ] Can't access app path '/Users/liuhaidl/Desktop/AMTools/SourceCodes/mobile/sampleApp/platforms/ios/build/device/sampleApp.app' : No such file or directory

Error: Error code 253 for command: ios-deploy with args: --justlaunch,--no-wifi,-d,-b,/Users/liuhaidl/Desktop/AMTools/SourceCodes/mobile/sampleApp/platforms/ios/build/device/sampleApp.app

Solution: sudo ionic run ios --device


Run Command: sudo ionic run ios

Check dependencies

Signing for "sampleApp" requires a development team. Select a development team in the project editor.

Code signing is required for product type 'Application' in SDK 'iOS 10.2'

The following build commands failed:

    Check dependencies
(1 failure)

Error: Error code 65 for command: xcodebuild with args: -xcconfig,/Users/liuhaidl/Desktop/AMTools/SourceCodes/mobile/sampleApp/platforms/ios/cordova/build-debug.xcconfig,-project,sampleApp.xcodeproj,ARCHS=armv7 arm64,-target,sampleApp,-configuration,Debug,-sdk,iphoneos,build,VALID_ARCHS=armv7 arm64,CONFIGURATION_BUILD_DIR=/Users/liuhaidl/Desktop/AMTools/SourceCodes/mobile/sampleApp/platforms/ios/build/device,SHARED_PRECOMPS_DIR=/Users/liuhaidl/Desktop/AMTools/SourceCodes/mobile/sampleApp/platforms/ios/build/sharedpch


No target specified for emulator. Deploying to iPhone-SE, 10.2 simulator//This is not a issue. It just shows you we have not set the certain iso version for simulator for it.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值