Pausing the android emulator
So like a lot of flash developers i’ve made the very easy transition into android development as of late. Mostly for personal interest as I now own an android phone, but also with an eye towards developing client applications as necessary.
The overall environment is a breath of fresh air compared to the flash authoring environment with one exception–the emulator is hugely slow. When I’m not doing anything experimental, the obvious workaround is to just test over USB to an actual phone. My N1 dev phone at work makes this even easier. Unfortunately I don’t always have that option, so I’m forced to test to the emulator. On my 6 core Mac Pro, this is really no problem, but when I’m out and about on a laptop, the extreme CPU usage of the emulator makes this problematic as it kills my battery rather quickly.
Thankfully, i found a relatively simple solution using the command line. To pause the emulator at any given time:
killall -STOP emulator
and to unpause it when you want to test:
killall -CONT emulator
if you aren’t comfortable with the command line or would rather kill the process entirely, you can also enable snapshots on the AVD, then make sure the startup is set to use the snapshots.
this takes slightly longer to restart, but its still a much more viable solution than attempting to reboot the emulator from scratch every time you want to test.
I would also be remiss as a developer if I didn’t state that the emulator is not the ideal testbed and you should test your application on as much actual metal as possible given the large variety of custom hardware and software that android is capable of running on.
Security Settings for Developers in Flash 10.3 Debug
Ever since 10.2 I’ve had issues with my old method of setting up security settings–which was pointing to the root of my workspace (ie Documents/Flash Projects or something similar) and never having to worry about loading local XML etc.
Now I get security warnings and I haven’t found a good solution until 10.3.
10.3 introduces the local control panel option for flash player, which in and of itself is nice since you don’t have to hit an external site to grab your settings. The developer settings can be found under the ‘advanced’ tab, and by scrolling down (its not immediately visible on the mac control panel–not sure about windows)
By browsing to the root of your hard disk or manually entering “/” as the path, you can now use all of your test files locally in a browser without having security exceptions thrown. Strangely this doesnt seem to work for any subfolder other than root. Even low level folders like the user folder on OSX yields incorrect results. Hopefully adobe will get around to fixing things to be slightly more secure in future versions, but for the time being that seems to be the only workaround.
Flash 10.x audio in windows 7 (no speakers)
Well here’s a new one for me…
My company has recently been producing a game for a client. We’re an all mac shop, so we have a few PC’s floating around in the corners for QA purposes. Last week one of the QA boxes kept failing miserably with the game engine over and over in the same spot. All of our macs and the rest of the PCs had no problem with the code. Finally I got fed up and installed the debug flash player on the QA box (we like to keep it as close to a user environment as possible–so they run stock FP) and sure enough caught some runtime errors coming from the audio engine.
After a bit of digging and a fair amount of guesswork, I gathered the other devs on the project around the machine and produced a pair of headphones. I plugged them into the rear audio port on the computer and retested the game with zero errors.
The other dev’s were confused for a minute until i explained what i had deduced… for some reason under windows 7 (and maybe vista as well, i have yet to test it) if you dont have headphones plugged in the driver seems to report this at a very low level to the flash player, which prevents any sound object from being initialized.
our stupid shortterm fix was just wrap the whole engine in a try catch (yeah–you dont have to tell me how stupid this is), but the long term fix is to make sure you check the result from new Sound() for nulls and shut down the engine accordingly.
Reflection and Annotations in AS3
I feel like there’s a fairly recent trend for flash developers to move into either IOS or Android development. Not being one to enjoy locked down platforms, I’ve been doing a bit of native (java not NDK) development on Android as well. I haven’t done any java since college so a bit of an updated was needed (it was java 1.1 when I was in school–feeling pretty old) So I had to dive headfirst into all of the new and awesome features in the latest version of java.
The first thing I didn’t have a lot of familiarity with was annotations. I was looking for a simple way to handle ORM between sqlite and native java code in android and a coworker (who is an enterprise java developer) recommended using annotations and reflection to make it happen. For those of you not familiar with java annotations are essentially classes that define meta data that doesn’t affect the inline code execution in any way, but can later be used via reflection to perform operations on the data contained within the decorated class. Sounds kinda funky so let me give a simple example:
public long id;
@DBUnique public long rId;
public String description;
public long catId;
public ItemType type;
public long dateTS;
public boolean isChecked;
public ItemVO(long id, long rId, String description, long catId, ItemType type, long dateTS) {
this.id = id;
this.rId = rId;
this.description = description;
this.catId = catId;
this.type = type;
this.dateTS = dateTS;
this.isChecked = false;
}
the @DBUnique is an example of an annotation placed in front of the id for this value object. This is later used by my ORM code to indicate to the sqlite storage code that this should be treated as a unique value for validation before an insert is attempted.
Okay so sure, thats fine for java, but this is a flash blog… how does this fit into flash. Well for years–literally since the bad old days of AS2 I’ve been ignoring the [Bindable] meta tag i see strewn throughout the as2 components and later as3 flex code. For those of you not familiar, this tag is used for data binding in flash/flex (which is a largely overused and intensive way of propagating data changes using Adobe’s largely memory inefficient event passing system). What I didn’t realize until working with java was that this is really not a compiler specific flag… you can put pretty much whatever you want in the tag and in as3 you can use reflection via the describeType method to then do something with it. Lets convert my java example over to as3 (perhaps for use in an air application with an sqlite db used for local storage).
public var id:int;
[DBUnique]
public var rId:int;
public var description:String;
public var catId:int;
public var type:ItemType;
public var dateTS:Number;
public var isChecked:Boolean;
public ItemVO(id:int, rId:int, description:String, catId:int, type:ItemType, dateTS:Number) {
this.id = id;
this.rId = rId;
this.description = description;
this.catId = catId;
this.type = type;
this.dateTS = dateTS;
this.isChecked = false;
}
in order to retain this metadata for runtime reflection you need to tell the compiler which annotations you are interested in… (kinda ironic that adobe optimizes for this given how they dont bother to optimize things like variable names which are for the most part stored inline in the bytecode) you can do that by passing the following in your flex compiler args: -keep-as3-metadata
in the Flash IDE it strips custom metadata by default, however you can work around this by checking the ‘export SWC’ box in your flash publish preferences. This retains all custom metadata and allows this to work in a more traditional compiler environment.
For the time being I don’t have any custom classes that take advantage of this, but I plan on writing a full reflection library simlar to java’s java.lang.reflect package so the output is at least strictly typed.
New (for me) Compilation Methodology for AS3
Introduction (rationale)
While I realize this isn’t new to most people its new and useful enough to my day to day that I thought I’d post about it. Most of my Flash career I’ve been working for big agencies or spinoffs of big agencies. One of the unfortunate realities of this situation is that most of the flash staff at any given agency came from a design background. Its often been a lonely road as someone with a mixed design/development background trying to enforce best practices and standards in organizations that are not structured to support it. As a result of this I’ve primarily been using the flash IDE or traditional Flex projects to do most of my compiling. This has been fine for most purposes, including the primary one: making it easy for non developer flash people to open and compile the code/make simple UI changes.
Thankfully there is some light at the end of the tunnel. I recently started a new job with some far more experienced flash team members and after an internal discussion we standardized on FDT4 pure actionscript 3 as our project standard. While i’ve been using FDT ever since I switched over to a mac for development, I’ve never used it to its fullest potential as we will see below:
How To
There’s a few steps to making this work in a viable way while still maintaining (comparatively) easy editing for your timeline or non technical flash people.
First: Compile all your graphical assets in a SWC to be used in the project as an asset library. To make an FLA export as a swc, edit its publish preferences then make sure the ‘export SWC’ is checked.
Next you’ll want to embed some actual assets in the library. I made a simple box for demonstration purposes then exported it in the library with the following settings:
Next you’ll want to set up a new project in FDT 4. You can just use the defaults as we are making an AS3 project.
I have 2 directories in my project structure that i use for external swcs: lib which contains swc or raw as3 libraries to be used in the project and assets which is used for all graphical assets including the assets.fla/swc used for vector assets in the project. This setup enables extremely fast compilation as well as the advantages of a command line compiler while still maintaining a certain level of edibility by timeline users.
Finally you need to set up a root class to be used as the Document class for the project. This is relatively simple. See my Example here… using a custom annotation to edit the output SWF. Note that the usual rules for document classes apply (must be a sprite or a movieclip)
Once your class is configured correctly, we need to add a new run configuration. if you click the tiny black arrow to the right of the large green ‘run’ arrow you can access the run configuration builder.
For this style of project we want to use the ‘FDT SWF Application’ template for our run configuration. Choose your project from the list, then choose the class that you previously created. You can also rename your output as desired.
Note that changing the output swf size in the annotation has no effect on the size of the output window that FDT opens for you when you compile. To change this you need to edit your run configurations again, click on the ‘start’ tab and change the size in this panel. (this is especially useful when doing liquid layouts)
You’re all set, just press the green run button and you should have a compiled swf! (assuming you dont have any errors in your code)
Conclusions
There are a variety of benefits achieved from this style of project compilation:
- Faster compile times
- Command Line compiler (for use in automated deployments like hudson)
- Easer ANT integration with pre/post compile ANT scripts
- Overall cleaner separation between presentation and logic
There are a few minor drawbacks as well:
- Explaining compile process to non-technical flash users
- asset swfs can get bloated/confusing rather easily without proper naming conventions
- most layout is done programmatically now which can take additional time (although not required)
So the advanced users reading this (that aren’t already laughing at me for wondering why it took me this long to switch over to this methodology) might also be wondering why i’m not using Flash Builder 4 for this same process since its not only natively supported, in FB4, but its also a default project type. The primary reason is that the FB4 compiler does a really funky job of non-realtime error checking. I’m used to realtime handling in eclipse for java projects so flipping over to FB4 is sort of like being slapped in the face. A single error on a seemingly unrelated class file will cause your entire project to blow up rather than just highlighting that error. The error messaging is reminiscent of the flash compiler, without the more obvious clues of the first error being the most likely place to look. Even with excellent plugins like SourceMate the experience is significantly less Eclipse like than I would prefer. Long story short even if you are a die hard flex fanatic you should check out FDT.
AS3 ampersands and GET requests with URLLoader
Working with a client’s REST api (using GET) I discovered a new and interesting issue that you’ll basically only encounter if you are being lazy like i was.
the client’s API urls were formatted something like this:
http://www.domain.com?key=1&key2=test&key3=blah
but with a ton more vars. most of the queries against their API were working fine, except for maybe 3 of the 15. Keep in mind I was taking a relatively lazy approach to grabbing the data by passing the full GET queryString into the new URLRequest() directly from the data model.
after some careful digging (with the help of charles) i noticed the ones that were failing had some escaped ampersands inline in them so the urls were something like:
http://www.domain.com?key=1&key2=test&key3=blah%20%26%20blah
where the %20 is an escaped space and the %26 is an escaped &.
when i looked at the request in charles I was seeing the same string, without the escaping being resolved into an & in the HTTP request. Dumping the exact same URL into firefox yielded the expected result of blah & blah in the request.
This led me to believe that flash’s URLLoader was the culprit. On a previous project using POST requests I was sending the data the “proper” way using the URLVariables object (found in flash.net package). On a whim I decided to try that using these requests. Since the number of variables in the GET request was extremely high, I was happy to notice in the documentation the decode method on the URLVariables class which allows for decoding an already properly formatted GET request (key value pairs) into the flash data format for a URLRequest. This can also be accomplished by passing the formatted string to the constructor of the URLVariables class.
My test code looked something like this:
var source:String = "http://www.domain.com?key=1&key2=test&key3=blah%20%26%20blah";
var loader:URLLoader = new URLLoader();
var temp:Array = source.split("?");
var urlPart:String = temp[0];
var varPart:String = temp[1];
var vars:URLVariables = new URLVariables( varPart );
var req:URLRequest = new URLRequest( unescape(urlPart) );
req.method = URLRequestMethod.GET;
req.data = vars;
loader.load(req);
you’ll note the rather odd presence of an unescape call in the constructor of my urlRequest. For some reason that I have yet to determine (the two strings looked identical) flash would not format the request properly without unescaping the input string. Overall this has been a very strange set of issues that I wish Adobe would have caught in their own debugging.
After a bit of trial and error I got the testbed working as expected, and converted it to a cleaner set of code for deployment.
Thoughts on Flash
A rebuttal to Steve Job’s long winded post which can be viewed here: http://www.apple.com/hotnews/thoughts-on-flash/
1) Flash is proprietary and closed. Sure, that’s true in the sense that the source for the IDE and some of the visual editors is not readily available. However there are a huge variety of 3rd party flash creation tools which output the same swf format that adobe themselves uses. Apple however does not allow this type of creation on their mobile platforms. Further the flex SDK and flex compiler are completely free to download… and are part of Adobe’s open source initiative: http://opensource.adobe.com/wiki/display/flexsdk/Flex+SDK. Translation: it might not be the worlds most accessible platform, but it sure is open.
2) Listing 10 sites that support h264 video a patented closed codec that Apple themselves is pushing does not in any way explain how apple supports “The full web”. Steve is quick to call out youtube as an example of h264 enabled site–unfortunately for his example not all of youtube’s content is available as h264. Additionally many popular 3rd party sites such as liveleak.com and collegehumor.com do not support h264. Of course this entire argument is structured around video, where the real context of the argument should be centered around all of the great interactive work that uses flash… none of which is accessible on Apple mobile devices. And really, lets examine Apple’s motives for why: is it really in their best interest to allow a huge amount of free content that is more interesting/entertaining than their current app store content that they are making 30% of each sale on?
Additionally, it is important to note that in the iPad’s current implementation of mobile safari the “Blue Lego” has been removed. Why would Apple take this away if there wasn’t user backlash against “missing” web content? Rather than rehash this argument I will simply link you to Grant Skinner’s excellent post on the subject: http://www.gskinner.com/blog/archives/2010/04/return_of_the_b.html
3) Security. Steve points fingers at Adobe’s less than stellar security record with flash. Unfortunately for him, all major flash security holes have been rapidly fixed… unlike those in OSX which caused it to be labeled as the least secure modern operating system by a security expert. Lets face it, they don’t even randomize the locations of libraries in RAM… leading to trivial buffer overflow exploits.
Performance. Steve attempts to claim that flash doesn’t run well on mobile devices. A few recent videos from Google showing 10.1 running on android 2.2 beg to differ. If there was really this massive performance hit Google wouldn’t be including it in ALL android with the 2.2 release.
4) Battery life (which is really part of the performance argument since this is really about software vs hardware decoding–but lest we forget, steve is not an engineer). Sure, hardware decoded video is faster and way way way more power efficient. So why did you choose to go with a proprietary and closed system (the apple A4) instead of adopting the Nvidia TEGRA 2 platform which supports flash video playback in hardware, and has been getting excellent reviews in early test units? Blaming Adobe for your own hardware choices seems to be fallacious at best.
5) Touch support. Flash 10 has full multitouch support for both raw touch data as well as specific gesture events. HTML5 supports neither.
6) Oh noes 3rd party IDEs making software on our platform. Again, this is a barely disguised move to attempt to make more iDevice exclusive content. By handicapping tools that are designed to make ALL mobile development streamlined for developers it forces the very people that Apple’s success has been based upon to bend over backwards to support their platform. Who would buy “Plants vs Zombies” in the appstore if they could play the flash version on their device (at 100% speed) for free? Its in Apple’s best interest to close down their platform. Unfortunately both the consumer and the developer suffers as Apple puts their own profits in front of the needs of the user.
Conclusions: HTML/Javascript were also created during the PC era. As such they have even less support for modern mobile/touch interfaces. HTML5 as a proposed standard sounds like an interesting idea. Unfortunately its not currently a standard, nor is it even up for ratification by the W3C until 2022. Claiming that your platform supports open “Standards” is disingenuous at best. Focusing the argument entirely on video again ignores not only the large variety of other sites that DO NOT support h.264 for video. It further ignores the vast wealth of free interactive content currently residing in the SWF format. Everything from games to tools, all of which would run fine on a properly supported platform with decent (tegra2) hardware support for the format.
As a developer–especially in such a rapidly moving technology segment as modern web development its important to stay current with all possible new technologies. As such I have built projects in HTML/CSS/javascript (jquery), HTML5 canvas experiments, as well as Microsoft Silverlight. The conclusions that I drew from this were that there are many exciting new technologies that have incredible (and often better) capabilities than the Adobe Flashâ„¢ platform. Unfortunately none of them are as easy to use for the graphic designers and non-coding animators that make up the backbone of the marketing and non-application Flash development community. Until a tool comes out that makes any of these technologies as accessible to non-developers as the Flash IDE has done throughout the years calling any of them “open” is not only foolish, its a disservice to the creative spirit that apple claims to nuture through their branding.
I challenge Steve Jobs to personally build 2 simple applications (i realize hes a busy man) in both technologies before making any wide, sweeping and completely uninformed statements about technologies that he has never used at anything but a consumer level.
edit: as a side note from conversations i’ve been having about this post… i forgot to mention that Apple’s own user experience department uses flash for prototyping. (thanks jef)
Overriding width and height properties on a displayObject
i’ve been using this trick for quite a while now, and while its easy to make some really dirty code with this, if its approached sensibly it can be a great timesaver.
I’ve found this approach to be effective in 2 specific scenarios:
- A gridded system with various scaling rules defined per column
- A complex animation scenario where items were animated in sequence but still had relative positioning based on other elements that may or may not be animating themselves
The code itself is really simple… extend a DisplayObjectContainer subclass (typically Sprite or MovieClip) and make sure you use the override keyword:
package {
import flash.display.Sprite;
class HeightOverrideExample extends Sprite {
private var items:Array;
public static const ITEM_HEIGHT:int = 20;
pubilc static const OFFSET:int = 50;
public function HeightOverrideExample() {
items = new Array();
}
public function addItem(__item:Sprite):void {
items.push(__item);
addChild(__item);
}
override public function get height():Number {
return OFFSET + (items.length * ITEM_HEIGHT);
}
}
}
in this example i’ve created a super simple example of a holder sprite which can have items added to it. in and of itself this is useless, but if one were to add animation to the addItem method its easily possible to find yourself in a situation where the height of the object is grabbed prior to the animation finishing causing some interesting (and unwanted) visual artifacts. One possible solution to this issue is to take advantage of the sequencing systems used in most modern tween engines and only grab the height of the clip once all internal animations have completed. Unfortunately this approach causes 2 problems: the clip itself cant be easily animated to relative positions while the previous internal animation is still running, and second the sequencing across 2 levels of display hierarchy causes severe dependencies in the code unless you use an Event based system.
Another use for this that i’ve had in the past is a gridding system where grid items follow various scaling rules depending on their column identifier. This is especially useful when dealing with proportionally scaled items like video that need to maintain a correct aspect ratio as the overall grid is shifting.
flash.net.Loader quickhits
a few random issues to note that i’ve come across in the past 6 months:
1) concurrent loaders or rapidly serial loaders on IE7 use massive amounts of CPU–upwards of 60% just for load operations (on a decently fast core2 machine as well)
2) URLRequest method being set to post only works if there is some kind of data in the data field, even if its a single space char… discovered this using a REST framework that required POST for all methods even when there was no input data.
Inheritance and “Automatically Declare Stage Instances”
One of the first problems I encountered when I started digging into AS3 oh so many years ago was that I expected inheritance to work just like java. It had been a while since I worked in java but the obvious similarities in the languages, and the newfound power of the AVM2 JIT model were exciting and heady things so I got right to work making a set of inherited button behaviors…
It was all well and good until I actually tried to compile the clip: error conflict exists in namespace blah blah… thanks Adobe. So whats the issue here? Adobe made an interesting design decision in CS3 onwards, more than likely out of respect for the designer based roots of Flash, in that all instances of graphics placed on the stage have declaration code written for them automatically at compile time.
So say you have a MovieClip on the stage with an instance name of myClip, Flash will generate the declaration code that you would normally write yourself in the parent clip… something alont the lines of: public var myClip:MovieClip.
So why does this cause problems with inheritance? I can’t say this with absolute certainty since I’m not privy to the internal workings of Flash, but my guess is that when it declares these public instances of your clip it does so at the highest level of inheritance. You can replicate the error that flash generates in this case by creating duplicate variable definitions in 2 classes and having one inherit the other:
public class Monkeys extends Primate {
public var monkeyGraphic:Sprite
}
public class Primate {
public var monkeyGraphic:Sprite
}
In any case, the solution to this is relatively simple, in the publish settings for the document, click on the flash tab, then the settings button next to the Actionscript 3, and finally uncheck the Stage: Automatically declare stage instances button.
Keep in mind that unchecking this will result in additional errors if your code does not declare other instances of clips that exist on the stage within custom classes that you have defined. Fortunately that doesn’t mean you cant give instance names to symbols or exported symbols on the stage that don’t have custom classes associated with them–you can still do that normally without any penalty.





