Adobe Flex Mobile: Detecting View and Orientation Change with Event Listeners

There will be a time when you want to have more control over the transitions between Adobe Flex Views, or detecting when the device orientation changes. For example, I recently built an app that had some event listeners that stayed persistent even when the user changed views. So, I needed to listen for the change event when using tabbed view navigator <s:TabbedViewNavigatorApplication/> so I could remove those event listeners and I did it like this:

this.addEventListener(Event.REMOVED_FROM_STAGE,tabChangeHandler);

I also had a need to detect when the phone was tilted. Yeh, in a perfect world everything in the app’s user interface would automatically adjust to the new state, but that isn’t always the case especially when building more complex apps. What I did was listen for orientation changes like this:

stage.addEventListener(StageOrientationEvent.ORIENTATION_CHANGE,stageOrientationChangeHandler);

Even if you are using some other Flex methodology for your mobile app, hopefully these examples will give you some ideas!

Running Android Apps Using External Storage (SD Card)

Hidden in the depths of the Android docs is an important chapter about info you need to know for running your apps off an external storage card. Here’s the link if you are a developer where you can use Manifest file settings so that anytime your app is installed it will be enabled for use on your SD Card: http://developer.android.com/guide/appendix/install-location.html . If you aren’t a developer then I can’t help you much because these settings require access to either the application source code, or the Android Debug Bridge.

You can also enable your apps for external storage from the adb command line using adb shell pm setInstallLocation 2. See the screenshot below. Once you’ve done that then use the adb install /mydir/some.apk to push the app to the phone. If the app isn’t automatically pushed to the card, then you’ll have to go into your droids application manager, select your application name, and then select “Move to SD”.

If you move the app to the external card you can find it using the built-in Android file browser under /mnt/asec/…

Here’s a quick link to Android dev docs on writing to internal and external storage. And, should you so desire to create a database on an external card you would point the SQLiteDatabase.openDatabase method to the appropriate directory path. I’ll point out that external storage is inherently insecure and you wouldn’t want to store passwords or anything important on it.

I’ll also add that not all storage cards are equal and some are much, much slower than others. Do your research, especially if you have a large application and you want snappy startup or read/write performance.

Presenting at the Esri Developer Summit

I’ll be presenting at the Esri Developer Summit this week (March 7 – 9, 2011) . So, if you are at the conference in Palm Springs, California stop by and say “hi”. If you aren’t familiar with this conference, it is the largest geo-developer conference in North America with over 1200 geo-geeks basking in all manner of technical geographic goodness. There will be 63 technical sessions and around 29 sessions presented by non-Esri, ArcGIS developers. What better way to learn than to hear it straight from the developers on the front lines…right??!

I have three sessions: a pre-conference session on Getting Started with the ArcGIS API for Android (beta), Localizing the ArcGIS Viewer for Flex, and integrated Volunteered Geographic Information and Social Media into your GIS. A GIS, is a Geographic Information System, for all you non-geo-geeks. Hope to see you there!

Check Network Connectivity in Your Android App

Our team does alot of application demos, and a vast majority of them require an internet connection. My challenge is that most of my development droid phones only have wireless (e.g. 802.11g), and I need a graceful way to detect if an internet connection exists. Without some sort of connection-based error detection, my mapping app would simply have a few buttons and a grey screen with no clue as to what the problem might be. So, here’s one way to to alert your users that the network connection is down. This was built using Android 2.2 on Eclipse 3.5.

Step 1 – Create a new Class that takes advantages of the capabilities in the ConnectivityManager class. That way you can reuse this across multiple projects. Be sure to import the appropriate references, and change the package name to the correct path in your project:

  
package com.esri.arcgis.android.samples;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class CheckConnectivity{
	ConnectivityManager connectivityManager;
	NetworkInfo wifiInfo, mobileInfo;

	/**
	 * Check for <code>TYPE_WIFI</code> and <code>TYPE_MOBILE</code> connection using <code>isConnected()</code>
     * Checks for generic Exceptions and writes them to logcat as <code>CheckConnectivity Exception</code>. 
     * Make sure AndroidManifest.xml has appropriate permissions.
	 * @param con Application context
	 * @return Boolean
	 */
	public Boolean checkNow(Context con){
		
		try{
			connectivityManager = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
			wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);	
			
			if(wifiInfo.isConnected() || mobileInfo.isConnected())
			{
				return true;
			}
		}
		catch(Exception e){
			System.out.println("CheckConnectivity Exception: " + e.getMessage());
		}
		
		return false;
	}	
}

Step 2 – Create an instance of that Class, and import the new Class you just created. Be sure to place your check for connectivity before any code that requires an internet connection. You can now use the Boolean result to decide what actions you want to take. I added the System.out.println to print the results into the logcat file. You can access logcat by installing Android Debug Bridge (ADB) and then typing “adb logcat” at a DOS command prompt. On a related note, you should also install Android Debug Tools (ADT) Eclipse Plug-in.

 @SuppressWarnings("serial")
public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);

     CheckConnectivity check = new CheckConnectivity();
     Boolean conn = check.checkNow(this.getApplicationContext());
     if(conn == true){
          //run your normal code path here
     }
     else{
          //Send a warning message to the user
          connectivityMessage("Check Network Connection."); }
}

public void connectivityMessage(String msg){
     Context context = getApplicationContext();
     Toast toast = Toast.makeText(context, "", Toast.LENGTH_LONG);
     toast.setGravity(Gravity.CENTER, 0, 0);
     toast.setText(msg);
     toast.show();
}

Step 3 – I did initially run into a problem where the application threw a strange “Source not found” error on a system thread. It say strange because there was absolutely no useful information. I knew the application ran just fine without my ConnectionCheck Class, so I used the step-thru debugger to narrow things down to my checkNow() method. I placed that in a basic try/catch block and walla there was the error with the solution:

I/System.out(  269): CheckConnectivity: ConnectivityService: Neither user 10032 nor current process has
 android.permission.ACCESS_NETWORK_STATE.
I/System.out(  269): CONNECTION CHECK: false

So, I went and added that permission line into the AndroidManifest.xml file and my app worked:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      android:versionCode="1"
      android:versionName="1.0" package="com.esri.arcgis.android.samples">
  	<uses-permission android:name="android.permission.INTERNET"/>
  	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable ="true">
        <activity android:name=".DrawGraphicElements"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="8" />
</manifest>

Here’s what the warning message will look like if you don’t have an internet connection:

The pace of technological change: Do Android’s really dream of electric sheep?*

Google’s Android v1.5 (Rev 1) was released in April 2009. In 2010, there were three major dot-X releases of the 2.x platform: v2.1, v2.3 and finally v2.3 in December 2010. According to Gartner in a February 2011 report, Android grew from 3.9% of the worldwide smartphone market, to almost 23% in the span of one year, from 2009 to 2010. That’s roughly 888% growth.

As a developer, I’m awed by the pace of change and the rate of adoption. I like being on the cutting, and now the consumer competition is furious for mindshare, and the mad push is on for developers to build applications that take advantage of the latest software and hardware technology. It’s a developers dream. Cool new toys, ever better functionality and hardware with new releases just six months away!

And while I like to simply pay attention to the technology and ignore everything else, I’ve been asked a number of questions recently by other developers who work in a variety of industries from around the world, and to which I have no answer. If you read this please share your thoughts:

  • How do we plan software development cycles around mobile phone system(s) that change dramatically every six months? We are talking about both hardware and software.
  • If I build an application now, will it still work on the next generation of hardware which will come out in one year or less?
  • Will applications that were built on the latest mobile OS still be backward compatible in one year?

What’s interesting is we have been faced with similar questions before when Adobe Flex, Microsoft Silverlight and even HTML 5 were announced. And, yes, they are changing the way we build applications and to a large extent changing what our users expect to experience. However, internet browsers have been around for a while, web development technologies in general aren’t exactly new, and all computers these days come with a pre-installed browser. But, all the sudden we could more quickly develop beautiful applications in days and weeks that used to take many months, or years. And, it’s been an eye-opener as far as our surfing experiences go.

Many commercial applications have never been more powerful with built-in charting and dynamic access to data with very graceful interfaces. These applications opened our eyes to what’s possible by letting us build applications independent of the machine they ran on. And, in a sense it was liberating. The idea of building one version of the software and then deploying it across many machines and devices became true. I, for one, touted that I no longer had to worry about esoteric items such as pointers and garbage collection. The browser took care of all that for the most part, even though it still had a few issues.

Maybe I celebrated too soon. What’s changing now is the pace of adoption which is in the form device that fits in your hand, and you can carry with you anywhere even when you hike, that accesses the internet, and that has similar functionality to a desktop/laptop system. Smart phone access is changing how people communicate: live, work and play. It’s becoming the primary connection to the internet in many parts of the world. It’s becoming a primary work tool while on the road.

We, as developers, are at the heart of this change and with a front row seat.

Our use cases are changing to accommodate people accessing our applications while they are standing in line ordering their morning coffee. We’re back to looking at native applications which don’t run in the browser and are subject to all sorts of interesting limitations and challenges. We are back to adapting code to different devices, limited battery life, testy internet connections, varying processor power, and dealing again with problems related to device drivers.

It’s funny that I caught myself thinking how nice it would be to have a software framework that would let me abstract away all these pesty problems that low-level code development entails: a sort of Flash Player environment for low-level code on a mobile phone. I mused about how easy it was to use FlashBuilder “Burrito” to convert my Adobe Flex applications directly to Android without having to deal with Java code (which works very nicely by the way). Or, do I build a rich functionality web app?

But, you know, I chuckled as soon as I had a requirement that asked for closer access to the smart phone hardware and operating system: things related to power management, and getting more information from the device GPS. Do I wait until the functionality I need is built into an abstraction library…or do I build a native application today? Which applications do I build for the web, and which application should be native?

These are all business question that many of you will also face. I’m certain it’s being asked thousands of times around the world. And ultimately, whatever the answer is… it will change the way we all do business.

*I pay full respect to Philip K. Dick’s 1968 science fiction novel, Do Androids Dream of Electric Sheep?, that served as the primary motivator for the movie Blade Runner which was first released in 1982.

Flash Builder Burrito makes Android mobile development easy

I had a brief encounter with Adobe’s Flash Builder Burrito during AdobeMAX. But this weekend was my chance to test drive it more fully and build an Android app from scratch. To be fair in this evaluation, I haven’t deployed a production-grade Android app…yet! I’ve really only touched the surface, and I’m sure there’s plenty of gotchas to come. But, first impressions are important and here are a few things I really liked about Flash Builder Burrito.

Likes

Very simple to get started. Check out the list of requirements:

  • Windows or Mac machine
  • FlashBuilder Burrito Preview Version

Take note that having an Android phone isn’t a requirement to get started, more on that in just a moment. If you do have an Android phone, then there are additional requirements:

  • Android with Froyo 2.2, AIR 2.5.x and/or Flash Player 10.1
  • USB driver for your model Android
  • Cable to attach your Android to your development machine
  • Network (for debugging)

At the time I’m writing this your deployment options include Flex, which will run in the Android’s Flash Player 10.1, or AIR 2.5.x, which runs locally on the device.

Makes use of existing Flex/ActionScript skills. I’m still very impressed with being able to use my existing Flex and ActionScript skills to essentially build a prototype mobile app in less than an hour and then deploy it to a phone for testing. When I first saw this at MAX it simply blew me away.

Built-in Emulator, no droid required. A very nice feature that Adobe added to Flash Builder Burrito is you don’t have to have an Android phone to get started building apps. It has a built-in emulator that currently lets you choose from 11 different Android platforms, such as Droid 2 and EVO. You can also easily switch from portrait view to landscape view to simulate turning your phone sideways. That was a simple thing, but a mandatory requirement for testing.

Sure, you’ll need a device to do field testing. For example, I wasn’t able to effectively use my emulator because my app required access to a device’s GPS. Once I deployed my test app to a device, then I was able to test the GPS functionality.

Dislikes

Granted this is a Preview release, there are still a few things I had problems with that would like to see added/changed in the final release.

Needs built-in advanced device debugging. The device debugging interface between Flash Builder Burrito and the Android phone is completely bare bones, absolutely no-frills…nada, zip. If you have any problem connecting to your phone it’s anyone’s guess as to what the actual problem is. You won’t get any useable feedback other than things won’t work. I spent four hours trying to troubleshoot why I couldn’t publish to my Droid 2, the launcher would simply hang.

I followed all the instructions carefully and rechecked them multiple times. I tried almost everything under the sun including multiple versions of the USB driver with reboot after reboot. I even installed the Android SDK and was able to successfully publish to my phone using the adb command-line interface. What finally fixed the problem was I upgraded the phone to AIR 2.5.1 on a whim. And presto, everything worked immediately!

It should be a requirement for Flash Builder to provide feedback about the device and provide hints on what might not be working and suggestions on how to solve the problem. Include something similar to adb devices, which would let me know that Flash Builder even recognizes the Android via USB. I’d also like to see something built-in similar to adb logcat that can provide real-time device feedback for every action that happens on the phone.  

Simplify the Android configurations. In Flash Builder Burrito, you have three specific configuration windows underneath the “Run” option. You have Profile, Run and Debug configurations that all have to be set up properly to make things work. This is really more of an annoyance than a showstopper. But streamlining workflows can save a boatload of time when you’re under the gun to deploy apps to a deadline. I’d like to see these combined into a single window, much like the Project > Properties window.

Improve access to the latest ActionScript mobile documentation. I haven’t yet found Flex/ActionScript 4.5 documentation, and I’m still looking. What I mean is if I type “ActionScript 4.5” into a search engine I expected to find the documentation. I also would like to see all classes and packages that work with AIR 2.5.x mobile in one single location. You can’t even easily find officially labeled Flex 4 documentation on the web, and I did relay this information to Adobe on several occasions. At one point I came across this page listed as documentation. What I did find was typically for ActionScript 3, AIR 2 (old!) and Flash Lite 4. And since that was old documentation, it wasn’t clear what had changed.  I also looked on the Flash Builder Burrito labs site here and the Mobile and Devices Developer Center here which is the first place I would expect a link to be.  

All-in-all it looks like a Adobe did a great job so far. So, that’s it for now since I need to get back to playing with my prototype app. If you have any other likes or dislikes please let me know.