zoukankan      html  css  js  c++  java
  • 跟我一起玩转Sencha Touch 移动 WebApp 开发(一)

    1.目录
    • 移动框架简介,为什么选择Sencha Touch?
    • 环境搭建
    • 创建项目框架,框架文件简介
    • 创建简单Tabpanel案例
    • 自定义图标的方式
    • WebApp产品测试和发布
    • HTML5离线缓存
    • 发布成Android/IOS本地app应用
    移动框架简介,为什么选择Sencha Touch?

    目前市面上,移动应用web框架,也算是风生水起,不断涌现,各个都称自己最牛逼。常见的几个框架主要有jquery Mobile,Dojo Moble,Sencha Touch,我这里是极端推荐Sencha Touch,至于它多优秀,不是我说了算,只有你亲自用过,做过项目之后才能领悟他的魅力;至于从没用过的口水党,请绕道。

    Sencha Touch是使用HTML5,CSS3和JavaScript来实现的,它可以在Android、IOS、WP、黑莓平台上使用,也可以在其他带有HTML5兼容的Web浏览器的平台上使用。更多详细介绍可以到官方阅读http://www.sencha.com/products/touch/,这里不罗嗦。

    至于我为什么选择Sencha Touch,理由有如下几点:

    • 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/

    2.确认本机安装了jdk1.6+,1.7最好

    3.Ruby1.9.3或者更早的版本,但一定不能安装2.0的,下载地址:http://rubyinstaller.org/downloads/

    4.android-sdk-tools,如果你不想打包成nativeApp,可以不用下载

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

    6.注意将jdk,ruby,sencha cmd都添加到环境变量

    Sencha Cmd 能干什么?详见:http://docs.sencha.com/touch/2.2.1/#!/guide/command

    创建项目框架

    ok,环境搭建完毕,下面我们通过sencha cmd(一下简称cmd)的一行命令创建项目框架

    #  首先确认进入到了sencha-touch-2-sdk
    cd /path/to/sencha-touch-2-sdk
    sencha 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 build
    102      */
    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 directory
    118      * must be kept intact for proper generation of deltas between updates
    119      */
    120     "archivePath": "archive",
    121 
    122     /**
    123      * List of package names to require for the cmd build process
    124      */
    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 element
    29         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/myapp
    sencha 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 chen
    What is the name of your organizational unit?
      [Unknown]: it
    What is the name of your organization?
      [Unknown]: hzy
    What is the name of your City or Locality?
      [Unknown]: jiaxing
    What is the name of your State or Province?
      [Unknown]:  zhejiang
    What is the two-letter country code for this unit?
      [Unknown]:  CN
    Is CN=Patrick Chu, OU=Training, O=Sencha, L=Redwood City, ST=California, C=US correct?
      [no]:  y
    
    Generating 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=CN
    Enter 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"
            ]
    }

    文件配置成功后,执行最关键的一步,打包命令

     如果全线飘绿,那恭喜你,你成功了,赶紧到uildMyApp ative目录下找你的apk吧,哈哈

    ok,安装到手机上,测试,一切正常,速度刚刚的,当然真正的和nativeapp比,必然会存在一些不足,但对于企业级的移动应用足够了。

    文章最后再爆一料,默认产生的app,安装到android后,title bar是没有隐藏的,这个你只需要去更改cmd的模版文件即可

    SenchaCmdSenchaCmd3.1.2.342stbuildst-resandroidAndroidManifest.xml,我想你该知道怎么做了吧!(*^__^*)

    OK了,本节基本上贯穿了整个Sencha Touch开发的全貌。

    下节课将会介绍真正的Sencha Touch细节开发了,深入到app里的各个层面(model,store,view,controller),注意事项,profile不同设备的适配等,敬请期待。

    能坚持看完的朋友,别忘了支持下哦

  • 相关阅读:
    PHP多维数组转为一维数组的方法实例
    PHP内存模拟分析
    linux windows mysql安装
    Ubuntu 连接Xshell 不能连接
    Linux软链挂载
    python 数据库连接 CRUD
    RabbitMQ 实现广播订阅
    Redis 实现广播订阅
    python-切片
    python中的3目运算(3元表达式)
  • 原文地址:https://www.cnblogs.com/qidian10/p/3294153.html
Copyright © 2011-2022 走看看