跟我一塊兒玩轉Sencha Touch 移動 WebApp 開發(一)

1.目錄
  • 移動框架簡介,爲何選擇Sencha Touch?
  • 環境搭建
  • 建立項目框架,框架文件簡介
  • 建立簡單Tabpanel案例
  • 自定義圖標的方式
  • WebApp產品測試和發佈
  • HTML5離線緩存
  • 發佈成Android/IOS本地app應用
移動框架簡介,爲何選擇Sencha Touch?

目前市面上,移動應用web框架,也算是風生水起,不斷涌現,各個都稱本身最牛逼。常見的幾個框架主要有jquery Mobile,Dojo Moble,Sencha Touch,我這裏是極端推薦Sencha Touch,至於它多優秀,不是我說了算,只有你親自用過,作過項目以後才能領悟他的魅力;至於從沒用過的口水黨,請繞道。css

Sencha Touch是使用HTML5,CSS3和JavaScript來實現的,它能夠在Android、IOS、WP、黑莓平臺上使用,也能夠在其餘帶有HTML5兼容的Web瀏覽器的平臺上使用。更多詳細介紹能夠到官方閱讀http://www.sencha.com/products/touch/,這裏不羅嗦。html

至於我爲何選擇Sencha Touch,理由有以下幾點:html5

  • Sencha 旗下的產品,若是你熟練Extjs,幾乎是零學習成本,平滑過渡到Touch開發,Sencha是一個很是活躍的組織,技術更新和支持都有很好的保障,世界財富100強裏,50%都在用他們的產品
  • 完美支持各大移動平臺Android、IOS、WP、BlackBerry等,同時能夠運行在任何HTML5兼容或以webkit爲內核的瀏覽器上(chrome,safari,360|搜狗極速模式)等,一次編寫,n次複用
  • 採用超強的cmd壓縮、Html5緩存和over-the-air技術,離線訪問,解決您對流量的擔心
  • 完美支持本地打包,一行命令便可將整個WebAPP打包成爲NativeApp,很是方便,不需作任何變動(令我震驚的是能夠直接經過ajax訪問遠程的服務沒有跨域問題)
  • MVC開發模式,充分解耦,井井有條
  • 針對不一樣平臺,區別對待,一個app,phone和tablet兩種展示
  • 便捷的Sencha Cmd命令工具,相似ruby的命令行,輔助開發
  • 豐富的報表控件
  • 業界最完備、精緻的API文檔,豐富的學習資料,幾乎一看就懂,強大的forum支持
  • 穩定性、JSONP、兼容性等小細節,堪稱完美
  • 等。
  • 更多介紹請看API:http://docs.sencha.com/touch/2.2.1/
環境搭建

1.下載sencha Touch SDK包http://www.sencha.com/products/touch/download/jquery

2.確認本機安裝了jdk1.6+,1.7最好android

3.Ruby1.9.3或者更早的版本,但必定不能安裝2.0的,下載地址:http://rubyinstaller.org/downloads/ios

4.android-sdk-tools,若是你不想打包成nativeApp,能夠不用下載web

5.Sencha Cmd 下載地址:http://www.sencha.com/products/sencha-cmd/downloadajax

6.注意將jdk,ruby,sencha cmd都添加到環境變量chrome

Sencha Cmd 能幹什麼?詳見:http://docs.sencha.com/touch/2.2.1/#!/guide/commandjson

 

建立項目框架

ok,環境搭建完畢,下面咱們經過sencha cmd(一下簡稱cmd)的一行命令建立項目框架

#  首先確認進入到了sencha-touch-2-sdkcd /path/to/sencha-touch-2-sdksencha generate app MyApp /path/to/www/myapp

ok,很簡單咱們生成了本身的項目架構,之後全部的開發都在這個項目架構中開發。

框架文件簡介

.sencha:cmd命令運行的一些配置參數

app:整個項目

resources:項目的資源文件,包括css,images,icons[app圖標],startup[啓動閃屏圖片]

touch:touch的核心包,源文件,資源文件等

app.js:整個項目的入口,配置了須要加載那些js文件等等

index.html:app啓動頁面

這裏須要重點講下app.json文件和packager.json文件

從st2.x開始,項目啓動時候加載的js,css等並不像之前同樣全都寫在index.html,而是經過app.json配置的形式來動態加載

st2.x的啓動加載方式有多種,你能夠參考http://www.cnblogs.com/dowinning/archive/2012/03/23/2413071.html

之因此保持官方這種方式,是由於後期咱們能夠直接經過cmd命令對項目壓縮發佈,或者打包等,若是破壞了目錄結構,cmd將沒法執行。

更詳細介紹請看官網:http://docs.sencha.com/touch/2.2.1/#!/guide/command_app

app.json淺析

經過IIS或者VS的IIS Express可能沒法加載該MIME類型,須要手工配置MIMEhttp://www.cnblogs.com/qidian10/p/3289816.html

  1 {  2     /**  3      * 程序名稱,由cmd時候定義產生  4      */  5     "name": "HzyApp",  6     /**  7      * 起始頁  8      */  9     "indexHtmlPath": "index.html", 10     /** 11      * The absolute URL to this application in development environment, i.e: the URL to run this application 12      * on your web browser during development, e.g: "http://localhost/myapp/index.html". 13      * 14      * This value is needed when build to resolve your application's dependencies if it requires server-side resources 15      * that are not accessible via file system protocol. 16      */ 17     "url": null, 18     /** 19      * List of all JavaScript assets in the right execution order. 20      * Each item is an object with the following format: 21      *      { 22      *          "path": "path/to/script.js" // Path to file, if local file it must be relative to this app.json file 23      *          "remote": true              // (Optional) 24      *                                      // - Defaults to undefined (falsey) to signal a local file which will be copied 25      *                                      // - Specify true if this file is a remote file which will not to be copied 26      *          "update": "delta"           // (Optional) 27      *                                      //  - If not specified, this file will only be loaded once, and 28      *                                      //    cached inside localStorage until this value is changed. 29      *                                      //  - "delta" to enable over-the-air delta update for this file 30      *                                      //  - "full" means full update will be made when this file changes 31      *          "x-bootstrap": true         // (Optional) 32      *                                      // Indicates a development mode only dependency.   33      *                                      // These files will not be copied into the build directory or referenced 34      *                                      // in the generate app.json manifest for the micro loader. 35      * 36      *      } 37      */ 38      /*應用中所須要的擴展的js文件*/ 39     "js": [ 40         { 41             "path": "touch/sencha-touch-all.js", 42             "x-bootstrap": true 43         },{ 44             "path":"common/Global.js", /*例如只是我本身定義的*/ 45             "update":"delta" 46         },{ 47             "path": "app.js", 48             "bundle": true, /*  Indicates that all class dependencies are concatenated into this file when build */ 49             "update": "delta" 50         } 51     ], 52     /** 53      * List of all CSS assets in the right inclusion order. 54      * Each item is an object with the following format: 55      *      { 56      *          "path": "path/to/item.css" // Path to file, if local file it must be relative to this app.json file 57      *          "remote": true             // (Optional) 58      *                                     // - Defaults to undefined (falsey) to signal a local file which will be copied 59      *                                     // - Specify true if this file is a remote file which will not to be copied 60      *          "update": "delta"          // (Optional) 61      *                                     //  - If not specified, this file will only be loaded once, and 62      *                                     //    cached inside localStorage until this value is changed to either one below 63      *                                     //  - "delta" to enable over-the-air delta update for this file 64      *                                     //  - "full" means full update will be made when this file changes 65      * 66      *      } 67      */ 68      /*應用中所須要的css文件*/ 69     "css": [ 70         { 71             "path": "resources/css/app.css", 72             "update": "delta" 73         },{ 74             "path": "resources/css/icons.css", /*例如只是我本身定義的圖標css*/ 75             "update": "delta" 76         } 77     ], 78     /** 79      * HTML5的緩存配置 80      */ 81     "appCache": { 82         /** 83          * 緩存的東西,即便離線任然可用http://www.cnblogs.com/qidian10/p/3292876.html 84          */ 85         "cache": [ 86             "index.html" 87         ], 88         /** 89          * 不緩存的東西,離線不可用 90          */ 91         "network": [ 92             "*" 93         ], 94         /** 95          * 錯誤頁面 96          */ 97         "fallback": [] 98     }, 99 100     /**101      * Extra resources to be copied along when build102      */103     "resources": [104         "resources/images",105         "resources/icons",106         "resources/startup"107     ],108 109     /**110      * cmd編譯項目時候,自動忽略的文件111      */112     "ignore": [113         "/.svn$"114     ],115 116     /**117      * Directory path to store all previous production builds. Note that the content generated inside this directory118      * must be kept intact for proper generation of deltas between updates119      */120     "archivePath": "archive",121 122     /**123      * List of package names to require for the cmd build process124      */125     "requires": [126     ],127 128     /**129      * Uniquely generated id for this application, used as prefix for localStorage keys.130      * Normally you should never change this value.131      */132     "id": "3c292300-172c-4bee-bbaa-d2e783f75677"133 }
View Code

app.json文件中注意js部分,默認開發的時候採用的是sencha.js,這將致使整個app加載js的時候都是加載st的源代碼文件,速度會很是慢,這裏我改爲sencha-all.js文件,直接加載他編譯好的包,效率將大大提高

packager.json該文件是爲了app打包用的,等到項目發佈的部分再解析

建立簡單Tabpanel案例

咱們打開app文件夾,在view裏面添加以下文件:

各個部分代碼以下:

 1 //<debug> 2 Ext.Loader.setPath({ 3     'Ext': 'touch/src' 4 }); 5 //</debug> 6 Ext.application({ 7     name: 'HzyApp', 8     requires: [ 9         'Ext.MessageBox'10     ],11     views: ['Main'],12     icon: {13         '57': 'resources/icons/Icon.png',14         '72': 'resources/icons/Icon~ipad.png',15         '114': 'resources/icons/Icon@2x.png',16         '144': 'resources/icons/Icon~ipad@2x.png'17     },18     isIconPrecomposed: true,19     startupImage: {20         '320x460': 'resources/startup/320x460.jpg',21         '640x920': 'resources/startup/640x920.png',22         '768x1004': 'resources/startup/768x1004.png',23         '748x1024': 'resources/startup/748x1024.png',24         '1536x2008': 'resources/startup/1536x2008.png',25         '1496x2048': 'resources/startup/1496x2048.png'26     },27     launch: function() {28         // Destroy the #appLoadingIndicator element29         Ext.fly('appLoadingIndicator').destroy();30         Ext.Viewport.add(Ext.create('HzyApp.view.Main'));31     },32    //html5緩存更新33     onUpdated: function() {34         Ext.Msg.confirm(35             "更新",36             "系統已經自動更新到最新版本,是否從新加載?",37             function(buttonId) {38                 if (buttonId === 'yes') {39                     window.location.reload();40                 }41             }42         );43     }44 });
app.js
 1 Ext.define('HzyApp.view.Main', { 2     extend: 'Ext.tab.Panel', 3     alias: 'widget.main', 4     requires: [ 5         'Ext.TitleBar', 6         'HzyApp.view.message.Main', 7         'HzyApp.view.history.Main', 8         'HzyApp.view.favorite.Main', 9         'HzyApp.view.system.Main',10         'HzyApp.view.user.Main'11     ],12     config: {13         id: 'hzyAppViewMain',14         fullscreen: true,15         tabBarPosition: 'bottom',16         items: [{17             xtype: 'messagemain'18         }, {19             xtype: 'systemmain'20         }, {21             xtype: 'favoritemain'22         }, {23             xtype: 'historymain'24         }, {25             xtype: 'usermain'26         }]27     }28 });
app/view/Main.js
 1 Ext.define('HzyApp.view.favorite.Main', { 2     extend: 'Ext.NavigationView', 3     alias: 'widget.favoritemain', 4     config: { 5         title: '收藏夾', 6         iconCls: 'favorites', 7         autoDestroy: false, 8         defaultBackButtonText: '返回', 9         navigationBar: {10             items: [11                 {12                     iconMask: true,13                     iconCls: 'refresh',14                     action: 'refreshKB',15                     align: 'right'16                 },17                 {18                     hidden: true,19                     iconMask: true,20                     iconCls: 'chat',21                     action: 'toreply',22                     align: 'right'23                 },24                 {25                     hidden: true,26                     iconMask: true,27                     iconCls: 'compose',28                     action: 'toscore',29                     align: 'right'30                 }31             ]32         },33         items: [34             {35                 html: 'This will display favorite urls!'36             }37         ]38     }39 });
app/view/favorite/Main.js

 

 其餘文件夾的main文件和favorite的相似,只須要改下標題和iconCls便可,下載地址:http://files.cnblogs.com/qidian10/view.rar

固然這些view、store、model、controller文件,你徹底能夠經過cmd命令建立

cd /path/to/www/myappsencha generate model User id:int,name,email
若是知道命令參數,直接輸入:sencha generate model

 

 ok,建立完成這些文件,你應該能夠看到本身的界面了,但遺憾的是估計你看不到你的圖標iconCls的圖標,應爲有兩個圖標是我自定義的。

SenchaTouch裏如何使用本身定義的圖標也是一門很大的學問,ST採用sass技術,圖標在2.2裏面所有改爲了字體的形式,也就是你看到的圖標實際上是一個字體(例如A)

自定義圖標的方式

 那麼如何在Sencha Touch 2.2 裏自定義icon圖標呢?提供一種簡單方法http://www.cnblogs.com/qidian10/p/3292669.html

 學會自定義icon後,將須要的icon,CSS加入到app.json的css塊中

WebApp產品測試和發佈

ok,不出意外,如今一個完整的demo應用已經展示在你面前了。

到目前爲止,若是你不嫌費流量和加載效率的話,其實一個應用已經完成了,你能夠直接用了。

可是Sencha給咱們提供了更加優秀的app發佈方式,能夠直接將項目中須要的資源壓縮打包,進行html5的離線緩存,這樣,咱們的應用程序在第一次加載完成後,在離線狀況下也是可使用的(數據訪問除外)

Sencha給咱們提供了4種發佈方式

  • testing:供測試,QA使用版本
  • package:脫離web server,本地html文件資源包
  • production:正是發佈的webapp產品
  • native:打包成android apk,或者ios app本地安裝文件

咱們只須要在cmd裏,執行一行命令便可發佈咱們的產品:

#production,testing,native,package#進入到你的經過cmd生成的MyApp文件夾中sencha app build production

 

ok,項目成功build,你可到MyApp/build/MyApp/Production中看生成的文件,你直接打index.html你會發現瞬間app就打開了,由於cmd幫咱們作了壓縮工做,全部的css,js都壓縮了,並且app的mvc核心文件都打包壓縮到app.js裏,減小了請求次數。

HTML5離線緩存

若是你將已發佈好的app,放到remote server上,第一次打開index.html,而後切斷網絡,再次刷新index.html你會發現仍然能夠顯示。緣由就是他採用了html5的離線緩存技術

Sencha Touch App每次打開都會檢查服務器是否有變更,若是有變更,會自動觸發app.js裏的onUpdated方法,提醒用戶更新

若是HTML5離線緩存小白的同窗,趕忙補課:http://www.cnblogs.com/qidian10/p/3292876.html

哦對了,這裏還須要添加MIME類型以支持html5的緩存變動文件cache.appcache,application/cache-manifest

發佈成Android/IOS本地app應用

若是你以爲採用webapp的方式,仍然不夠理想,那麼能夠用st的另外一把利器,打包Sencha Touch webapp爲本地native app

這裏介紹如何將Sencha Touch 打包爲Android的apk

首先確認安裝了android-sdk-tools,jdk,下面開始本節的最後一個內容:

1.生成android證書

  簡單起見,咱們將私鑰倉庫(keystore)創建在X:/目錄,將私鑰倉庫(keystore),別名(alias) 和密碼(password)都設爲"hzyapp"。

$ keytool -genkey -v -keystore hzyapp.keystore -alias hzyapp -keyalg RSA -keysize 2048 -validity 10000

Enter keystore password: (I entered "hzyapp")What is your first and last name?  [Unknown]: jack chenWhat is the name of your organizational unit?  [Unknown]: itWhat is the name of your organization?  [Unknown]: hzyWhat is the name of your City or Locality?  [Unknown]: jiaxingWhat is the name of your State or Province?  [Unknown]:  zhejiangWhat is the two-letter country code for this unit?  [Unknown]:  CNIs CN=Patrick Chu, OU=Training, O=Sencha, L=Redwood City, ST=California, C=US correct?  [no]:  yGenerating 2,048 bit RSA key pair and self-signed certificate (SHA1withRSA) with a validity of 10,000 days    for: CN=jack chen, OU=it, O=hzy, L=jiaxing, ST=zhejiang, C=CNEnter key password for <hzyapp>    (RETURN if same as keystore password):  [Storing hzyapp.keystore]

 ok,這樣你就產生了一個hzyapp.keystore證書,備用。

上面咱們講到還有一個文件packager.json沒解析,這裏解析下,該文件就是打包本地應用的配置文件,打開文件內容配置對android的配置以下:

{    "applicationName":"HzyApp",    "applicationId":"com.hwayifashiongroup.HzyApp",/*必須是包括兩個點*/    "bundleSeedId":"KPXFEPZ6EF",    "versionString":"1.0",    "versionCode":"1",    "icon": {        "36":"resources/icons/Icon_Android36.png",        "48":"resources/icons/Icon_Android48.png",        "57":"resources/icons/Icon.png",        "72":"resources/icons/Icon~ipad.png",        "114":"resources/icons/Icon@2x.png",        "144":"resources/icons/Icon~ipad@2x.png"    },    "inputPath":"./",    "outputPath":"../build/",    "configuration":"Debug",    "platform":"Android",/*平臺,還有IOS等類型*/    "certificatePath":"X:/hzyapp.keystore",/*證書*/    "certificateAlias":"hzyapp",/*證書別名*/    "certificatePassword":"hzyapp",/*證書密碼*/    "sdkPath":"D:/GreenSoftWare/Android/android-sdk-windows",/*android-sdk路徑*/    "androidAPILevel":"8",/*Android版本,我用了2.2*/    "permissions":[            "INTERNET",            "ACCESS_NETWORK_STATE",            "CAMERA",            "VIBRATE",            "ACCESS_FINE_LOCATION",            "ACCESS_COARSE_LOCATION",            "CALL_PHONE"        ]}

文件配置成功後,執行最關鍵的一步,打包命令

 若是全線飄綠,那恭喜你,你成功了,趕忙到/build/MyApp/native目錄下找你的apk吧,哈哈

ok,安裝到手機上,測試,一切正常,速度剛剛的,固然真正的和nativeapp比,必然會存在一些不足,但對於企業級的移動應用足夠了。

文章最後再爆一料,默認產生的app,安裝到android後,title bar是沒有隱藏的,這個你只須要去更改cmd的模版文件便可

SenchaCmd/Sencha/Cmd/3.1.2.342/stbuild/st-res/android/AndroidManifest.xml,我想你該知道怎麼作了吧!(*^__^*)

 

OK了,本節基本上貫穿了整個Sencha Touch開發的全貌。

下節課將會介紹真正的Sencha Touch細節開發了,深刻到app裏的各個層面(model,store,view,controller),注意事項,profile不一樣設備的適配等,敬請期待。

能堅持看完的朋友,別忘了支持下哦

相關文章
相關標籤/搜索