现在的位置: 首页 > 综合 > 正文

[Professional.Flash.Mobile.Development]

2013年10月06日 ⁄ 综合 ⁄ 共 13982字 ⁄ 字号 评论关闭

----------------第三章----------------------

手势为多点触控的默认

MultitouchInputMode.GESTURE (thedefault, by the way)

            sprite.addEventListener(TransformGestureEvent.GESTURE_ZOOM, zoomHandler); 
            sprite.addEventListener(TransformGestureEvent.GESTURE_PAN, panHandler); 

----------------第四章----------------------

 The following are general AS3 tips to consider: 

     ??     Always use the most efficient data type possible when working with variables. A Number is less efficient than uint or int, and a Vector is preferred over an Array. 
     ??     For string searching and management, use string methods (such as indexOf()) rather than working with less efficient regular expressions. 
     ??     When you do need to create objects, try to create them outside of loops. 
     ??     Referencing
an object using square brackets slows performance
. Therefore, notice the mul
tiple references
using square brackets in the for loop here: 

                public processFeeds(feeds:Vector.<Feed>):void 
                 { 


                  var feed:Feed;  
                  var count:int = feeds.length;    


                  for (var i:int=0; i<count; i        ) 
                  { 


                       feeds[i].name = “RSSFeed1”;  
                       feeds[i].url = “www.myfeed.com/rss”  
                       feeds[i].fetch();  
                     } 
                   } 

               A more efficient way to write would be as follows: 

                   public processFeeds(feeds:Vector.<Feed>):void 
                   { 

                     var feed:Feed;  
                     var count:int = feeds.length;    


                     for (var i:int=0; i<count; i         ) 
                     { 
                       feed = feeds[i];  
                       feed.name = “RSSFeed1”; 
                       feed.url = “www.myfeed.com/rss”  
                       feed.fetch();  
                     } 
                   } 

       ??     When you are working with loops, avoid evaluations when possible. A common issue would be when you are iterating through an array and you use this: 

                   for (var i:int=0; i<feeds.length; i  ) 
                   { 
                       // loop  
                   }  

               Instead, a more efficient way would be to assign the value of the evaluation first to a local variable, and then use that variable in the loop: 

                   var count:int = feeds.length;  
                   for (var i:int=0; i<count; i        ) 
                   { 
                       // loop  
                   } 

       ??      Function calls are more expensive than placing all or the majority of your code in one procedural unit. Minimizing functions improves speeds significantly in certain cases, but it comes at a significant cost from a code architecture
and maintainability standpoint. But if you are struggling with performance and have tried everything else, function calls are your panic button. 

       ??      Be careful with any kind of timer activity you want to perform. Timers are acceptable for nonanimated apps in which the increment for the timer is fairly long. For animated apps, consider attaching a listener to the Event.ENTER_FRAME event, which
is dispatched for every  new frame. However, timers do consume more CPU cycles than attaching a listener to an ENTER_FRAME event, so be prudent in their usage, especially if the timer increment is less than
100 ms. If you have to use a timer, use a centralized one for all your  app’s time-related tasks. 

        ??       Avoid assigning a TextField’s text property inside a loop. Instead, assign the value to a string variable, and then assign it to the text property outside the loop. 

        ??       If you animate your text, boost performance by removing transparency settings and assigning  an opaqueBackground property to a color value, which disables the alpha properties. What’s more, set the cacheAsBitmap to true so you can cache
the text content as bitmaps. 

Silently play any sounds you plan to use when the app is launched so that they are cached in memory. This preloading trick helps eliminate the chance of a lag when the sound is played the first time. 


----------------第五章----------------------

      You can capture TouchEvent events for finger pressing instead ofMouseEvent events. However, as a general rule, if you’re just listening for basic button
clicks and so on,use MouseEvent events when possible, because they are less expensive


    To listen for mouse events only and not listen for touches and gestures, use this: 

         Multitouch.inputMode=MultitouchInputMode.NONE 

    To listen for single touches, use this: 

         Multitouch.inputMode=MultitouchInputMode.TOUCH_POINT 

    To listen for gestures, use this: 

         Multitouch.inputMode=MultitouchInputMode.GESTURE 


冒泡事件优化

You can minimize event bubbling by flattening the display object hierarchy as much as possible. What’s more, it’s a good practice to handle the event in the intended target display object and then stop the event bubbling by calling the event object’sstopPropagation()method. 

手势的swipe事件

                if (Multitouch.supportsTouchEvents) 
                {     
                    Multitouch.inputMode = MultitouchInputMode.GESTURE; 
                    stage.addEventListener(TransformGestureEvent.GESTURE_SWIPE, 
             swipeHandler); 
                } 

        private function swipeHandler(event:TransformGestureEvent):void  
            {                              
                // Swipe Left  
                if (event.offsetX == 1 )  
                { 
                   ///////////////////////               
          }                             
          //Swipe Right                              
          else if (event.offsetX == -1)  
          { 
             //////////////////
          } 

      } 

Use the offsetX property of the TransformGestureEvent object to determine the direction of the swipe.A value of 1 indicates that the swipe is leftward, whereas a value of –1 indicates a swipe to the right. 

----------------第六章----------------------

Accelerometer的用法

if (Accelerometer.isSupported)  { 
                 accelerometer = new Accelerometer();  
                 accelerometer.setRequestedUpdateInterval(500);  
                 accelerometer.addEventListener(AccelerometerEvent.UPDATE,accelerometerUpdateHandler); 
                 }

----------------第七章----------------------

自动转向的用法

                try 
                { 
                    stage.addEventListener(StageOrientationEvent.ORIENTATION_CHANGE, orientationChangeListener); 
                    print(“Rotate me”); 


                } 
   public function orientationChangeListener(event:StageOrientationEvent):void 
   {
               if(event.afterOrientation) {
           if (stage.orientation == StageOrientation.DEFAULT || stage.orientation == StageOrientation.UPSIDE_DOWN) { ////////////// } 
          else if (stage.orientation == StageOrientation.ROTATED_RIGHT || stage.orientation == StageOrientation.ROTATED_LEFT) { /////////////// }

Android does not currently support the following ScreenOrientation constants:   

            ScreenOrientation.ROTATED_LEFT               ScreenOrientation.UPSIDE_DOWN             ScreenOrientation.UNKNOWN 


----------------第八章----------------------
关于GPS调用
修改xml配置文件

         <android> 
             <manifestAdditions> 
               <manifest> 
                 <data> 
                   <![CDATA[ <uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” /> ]]> 
                 </data> 


                  </manifest> 
                </manifestAdditions> 
              </android> 
 if (Geolocation.isSupported) 
         { 
             // If so, set it up.  
             geo = new Geolocation(); 
             geo.setRequestedUpdateInterval(500); 
             geo.addEventListener(GeolocationEvent.UPDATE, geolocationUpdateHandler); 
             geo.addEventListener(StatusEvent.STATUS, geolocationStatusHandler); 

          

----------------第九章----------------------

电话:

 public static function dial(phoneNumber:String):void 
                    { 
                        // In a real-world situation, you’d want to add 
                        // validation to the phone number  
                        var cmd:String = “tel:” + phoneNumber;  
                        executeCommand(cmd);              
                    } 

The dial() method takes a phone number as a parameter, adds the tel: protocol to it, and then passes that ontoexecuteCommand().

发短信:

           <android> 
             <manifestAdditions> 
               <manifest> 
                 <data> 
                 <![CDATA[ 
                   <uses-permission android:name=”android.permission.INTERNET”/> 
                 ]]> 
                 </data> 
               </manifest> 
             </manifestAdditions> 
           </android>
 var cmd:String = “sms:” + phoneNumber;  
                     executeCommand(cmd);               
private function btnSMSMouseClickHandler(event:Event):void 
          { 
             event.stopPropagation(); 
             SMS.send(tiNumber.text);           
         }  

发邮件:

               public class Mail extends MobileService 
               { 
                    
                   public static var recipient:String = null;   
                   public static var ccList:String = null;  
                   public static var bccList:String = null;          
                   public static var subject:String = null;  
                   public static var body:String = null;  

                   /** 
                    * Opens the Mail app and provides message details based on  
                    * the class static properties.   
                    *  
                    */ 
                   public static function sendMail():void 
                   { 
                       var cmd:String = “mailto:”;  
                        
                       var firstParam:Boolean = false;  
                        
                        
                       if (!recipient) 
                       { 
                           trace(“Error: You need to specify one or more recipients.”); 
                           return;  
                       }     

                       // Add recipient list  
                       cmd += recipient;  

                       // Add subject  
                       if (subject)  
                       { 
                           var subjectArr:Array=subject.split(‘ ‘); 
                           subject = subjectArr.join(‘%20’); 
                            
                           cmd+= “?subject=” + subject;  
                           firstParam = true;  
                       }     
                        
                       if (ccList)  
                       { 
                           var ccListArr:Array=ccList.split(‘ ‘); 
                           ccList = ccListArr.join(‘%20’); 
                            
                           if (!firstParam)  
                               cmd += “?cc=” + ccList 
                           else 
                               cmd += “&cc=” + ccList;  
                            
                           firstParam = true; 
                       }     
                        
                       if (bccList)  {
                          var bccListArr:Array=bccList.split(‘ ‘);        
                          bccList = bccListArr.join(‘%20’); 
                          if (!firstParam)   cmd += “?bcc=” + bccList;
                          else   cmd += “&bcc=” + bccList; 
                          firstParam = true; 
                       } // Add message text  

                  if (body){  
                      var bodyArr:Array= body.split(‘ ‘);
                      body = bodyArr.join(‘%20’);
                      if (!firstParam)     cmd += “?body=” + body;
                      else    cmd += “&body=” + body; 
                  } 
                  executeCommand(cmd); 
            }
}


         mailto:rich@mycompany.com?subject=s1%20s2& cc=c1&bcc=b1%20b2%20b3&body=massage1%20ms2

package 
      { 
          import flash.display.Sprite; 
          import flash.events.MouseEvent; 
          import flash.events.Event;
          import com.richwagner.mobileservices.Mail; 

          public class KindaSortMail extends Sprite{
             public function KindaSortMail(){
                 btnSend.addEventListener(MouseEvent.CLICK, sendClickHandler); 
             }
             private function sendClickHandler(event:Event):void{
                 Mail.recipient = tiRecipient.text;
                 Mail.subject = tiSubject.text; 
                 Mail.ccList = tiCcAddress.text; 
                 Mail.bccList = tiBccAddress.text; 
                 Mail.body = taMessage.text;
                 Mail.sendMail(); 
            }
          }

使用googleMap

public static function pointToCoordinates(latitude:Number,longitude:Number):void 
                   { 
                       var cmd:String = “http://maps.google.com/maps?q=”latitude.toString() + “,” + longitude.toString();  
                       executeCommand(cmd);  
                   }  

----------------第十一章----------------------

SD [Secure Digital] card

a File object points to either a directory or a file

you can use the resolvePath() method to access a subdirectory or file inside of it.

      private var storeDir:File = File.applicationStorageDirectory; 
      private var prefXML:File = storeDir.resolvePath(“preferences.xml”); 

Creating a directory 

         var dataDir:File = File.applicationStorageDirectory.resolvePath(“data”); 
         dataDir.createDirectory();  

Creating a directory 

var tmpDir:File = File.createTempDirectory(); 
var tmpFile:File = File.createTempFile(); 

creates a uniquely named subdirectory inside the app’s temporary directory. (For Android apps, that will be located in/data/data/app.appId/cache.)

Be sure to clean up your temporary files and directories when you are finished with them or when the app closes. Theyaren’t removed automatically

复制与移动文件

Synchronous Operations

            var sourceFolder:File = File.applicationStorageDirectory.resolvePath(“data”); 
            // Note: documentDirectory not supported under iOS  
            var targetFolder:File = File.documentsDirectory.resolvePath(“data”); 
            sourceFolder.copyTo(targetFolder); 

覆盖已存在文件

 sourceFolder.copyTo(targetFolder, true); 

移动文件的话就把copyTo替换成moveTo

Asynchonous Operations:

     public function createBackupCopy():void  
      { 
       // Note: documentDirectory not supported under iOS  
       var originalFile:File = File.documentDirectory.resolvePath(“MyApp/data.sql”); 
       var backupCopy:File = 
         File.applicationStorageDirectory.resolvePath(“Backup/backup01.sql”); 

       originalFile.addEventListener(Event.COMPLETE, copyCompleteHandler); 
       originalFile.addEventListener(IOErrorEvent.IO_ERROR, copyErrorHandler); 
       originalFile.copyToAsync(backupCopy); 
      } 

     public function copyCompleteHandler(event:Event):void  
      { 
       trace(“Backup operation completed successfully”);  
      }       

     public function copyErrorHandler(event:IOErrorEvent):void  
      { 
       trace(“Operation failed.”); 
      } 

   deleting Files and directories :
      When using AIR for desktop operating systems, you have the option of deleting a file (deleteFile() anddeleteFileAsynch()) or sending it to the Trash/Recycle
Bin (moveToTrash() andmoveToTrashAsync()). However, because there isno Trash/Recycle Bin concept in the Android OS or
iOS
, themoveToTrash() andmoveToTrashAsync() methods behave in the same manner as their delete counterparts. 

      The following code evaluates a file to determine if it’s a file or directory. It then issues the appropriate delete command: 

            var tempFile:File = File.createTempFile(); 
             // do something with tempFile, then… 
             if (tempFile.isDirectory() == true) 
                tempFile.deleteDirectory(true) 
            else  
                tempFile.deleteFile(); 

        ??      FileMode.READ indicates that the file is open for reading only. 

        ??      FileMode.WRITE specifies that the file is open for write access. If the file already exists, its contents are deleted. If the file does not exist, it is created. 

        ??      FileMode.APPEND specifies that the file is to be opened in “append mode” — in other words,new data is added to the end of the file rather than overwriting existing data. If the file does not
exist, it is created. 

        ??      FileMode.UPDATE indicates that the file is open for both reading and writing. This mode is used when you need random read/write access to the file. When you write to the file, only the bytes
at the current location are overwritten, not the entire file. If the file does not exist, it is created. 

          var file:File = File.applicationStorageDirectory.resolvePath(“preferences.xml”); 
          var fileStream:FileStream = new FileStream();  
          fileStream.open(file, FileMode.WRITE); 

----------------第十一章----------------------

建立数据库连接

           var sqlConnection:SQLConnection = new SQLConnection();  
           var databaseFile:File = File.applicationStorageDirectory.resolvePath(“vheissu.db”); 
            sqlConnection.open(databaseFile); 

异步连接:

var databaseFile:File =File.applicationStorageDirectory.resolvePath(‘vheissu.db’); 
             sqlConnection = new SQLConnection();  
             sqlConnection.addEventListener(SQLEvent.OPEN, databaseOpenHandler);  
             sqlConnection.addEventListener(SQLErrorEvent.ERROR, databaseErrorHandler);  
             sqlConnection.openAsync(databaseFile);
 

执行SQL语句:(For more information on SQLite, go to www.sqlite.org.

 // Feeds table  
         var createTable1: SQLStatement = new SQLStatement(); 
         createTable1.sqlConnection = _connection; 
         createTable1.text = 
             “CREATE TABLE IF NOT EXISTS feeds (“ +  
             “    uid INTEGER PRIMARY KEY, “  
             “    url TEXT UNIQUE, “ +  
             “    name TEXT, “ +  
             “    logoUrl TEXT, “ +  
             “    lastFetched DATE “  +
                “)”; 
            createTable1.execute(); 

注释:若不存在表feeds,则执行语句

带变量的SQL语句

            const SELECT_ENTRIES_BY_FEED_ID:String =“SELECT * FROM feedEntries WHERE feedId = :feedId”;  

            var sqlStatement:SQLStatement = new SQLStatement(); 
            sqlStatement.sqlConnection = _connection;  
            sqlStatement.text = SELECT_ENTRIES_BY_FEED_ID;  
            sqlStatement.parameters[“:feedId”] = feed.uid; 
            sqlStatement.execute();

            var sqlResult:SQLResult = sqlStatement.getResult(); 
            var entries:Array = sqlResult.data;  

注意feedId带有

而返回的数据每个条目都包含以下信息:

                 guid = itemInfo.guid;  
                           url = itemInfo.url;  
                           title = itemInfo.title; 
                           text = itemInfo.text; 
                           timestamp = itemInfo.timestamp; 
                           thumbnailUrl = itemInfo.thumbnailUrl; 
                           author = itemInfo.author;  
                           authorUrl = itemInfo.authorUrl;  
                           category = itemInfo.category;  
                           wasRead = itemInfo.wasRead; 

SQLLite中的事务替代方法

由于SQLite中SQL语句不支持事务,我们可以通过SQLConnection类的与事务相关的方法可使用此功能:SQLConnection.begin()、SQLConnection.commit() 和SQLConnection.rollback()来实现事务功能。

		_connection.begin();     
		///
               _connection.commit();  

要么全部执行要么都不执行

   try
   {
    con.open(file);
    
    con.begin();
    stmt.sqlConnection=con;
    stmt.text="INSERT INTO emp (firstName, lastName, salary) VALUES ('f', 'l', 1110)";
    stmt.execute(); 
    con.commit();  
   }
   catch(err:SQLError)
   {
    con.rollback();
    Alert.show(err.message);
   } 
} 

代码说明
事务由begin方法开始,其间运行的n个sql语句要是成功,就由commit方法提交,其间要是有任何一个sql语句发生错误,就由rollback方法全部回滚。

基本SQL语句

SELECT * FROM feedEntries WHERE feedId = 100  

 REPLACE INTO feeds (uid, url)  VALUES (:uid, :url);  

 INSERT INTO feeds (uid, url)  VALUES (:uid, :url);  

UPDATE feeds (uid, url)  VALUES (:uid, :url);  

UPDATE:若本项存在则更新,不存在则不作为;INSERT:插入;REPLACE:若本项存在则覆盖,不存在则插入;

---------------------华丽丽分割线----丈二和尚摸不着头脑---------------------


改框框的时候遇到一个哭笑不得的问题。air2.5可以成功编译运行,2.6跟for android就不行。一开始没发现是版本的问题,还一直找错...于是一直切换编译器导致同样代码一会儿可以一会儿瘫痪卧槽...试了很多办法无奈把类名Json改成Json1居然没问题了...莫非Json变成新的保留字了不成?or或者变成内置类了?

---------------------华丽丽分割线----消失的右键菜单---------------------

移植的时候碰到个问题居然是右键菜单导致的...编译的时候居然还乱提示,抓到文件流的错误害我还以为是读取外部文本出错= =喵了个咪的

---------------------华丽丽分割线----为FlashCS5.5增加新版Player支持---------------------

http://bbs.9ria.com/thread-98967-1-1.html

抱歉!评论已关闭.