Showing posts with label android. Show all posts
Showing posts with label android. Show all posts

Monday, June 17, 2013

Announcing: Android Training at Chariot Solutions

We are pleased to announce Android developer training at Chariot Solutions, starting July 22, 2013.

The course curriculum covers the gamut from user interface design, to access of sensors and features of your devices, and to network access and local storage.  We use courseware designed for phones and tablets, including modern fragment-based layout design.

Several dates are available on the Android Training course page.

Here is a condensed course outline:

Chapter 1. The Android Operating System 

Mobile Form Factors * Versions of Android * Applications and APK Files * Process Architecture * The Role of Java * Hello, Dalvik * What's In, What's Out * Services * User Interface * Memory and Storage * Operating-System Services * Inter-Process Communication

Chapter 2. Android Development 

The Android SDK * The SDK and AVD Managers * Configuring the Emulator * Eclipse * Resources * APK Files * Build Process * The R Class * Assets * The Dalvik Debug Monitor Server * The Android Debugger (adb) * Command Shells * The Android Log and LogCat * Ant

Chapter 3. Applications 

Activities and Fragments * Activity Lifecycle * The onCreate Method * Layouts and Views * The findViewById Method * Tasks and the "Back Stack" * Intents and Results * startActivity and Related Methods * Custom Application Classes * Shared Application State

Chapter 4. User Interface Design

XML Layouts * Layout Parameters * The Box Model * Gravity * The LayoutInflater Service * The <LinearLayout> * The <RelativeLayout> * Views and Adapters * Form Widgets

Chapter 5. Fragments and Multi-Form Design 

The Fragments API * Fragment Lifecycle * Relationship Between Activity and Fragment * Possible Cardinalities * Communication between Activity and Fragment * Fragment Arguments * Callback Interfaces * Designing for Multiple Form Factors * Fragments on the Back Stack

Chapter 6. Working with Lists

AdapterView and Subclasses * Adapter and Subinterfaces * ListView and ListAdapter * ListFragment * Spinner and SpinnerAdapter * Handling Item Selection * Custom Adapters * ExpandableListView and ExpandableListAdapter

Chapter 7. Menus and the Action Bar

Options and Context Menus * The Action Bar * Menu Resources * The MenuInflater Service * The <Menu> * The Menu and MenuItem Classes * Handling Menu Selections * The Escape from switch/case! * Using a Dispatch Map * Building Menus Dynamically

Chapter 8. Local Storage

The Android File System * Internal Storage * File Formats * Parsing JSON * Storage and the Application Lifecycle * External Storage * Private Storage vs. Public Media * Permissions * Checking for Availability

Chapter 9. Networking and Web Services

java.net * android.net * Apache HttpClient * Consuming RESTful Web Services * Building URLs * Parsing JSON * Parsing XML * Connected Applications * Offline Operation and Server Synchronization

Chapter 10. Asynchronous Tasks

The UI Thread * Background Tasks * Loopers and Handlers * Using AsyncTask * Using ProgressDialog * Error Handling

Chapter 11. Multimedia 

Playing Sounds * Haptic Feedback (Vibrating) * Managing Images * Storage and Retrieval * Invoking the Camera * Invoking the Media Recorder * Gallery and other Image Views

Chapter 12. Location Services and Maps 

Location Services * Location Notifications * The Google Maps API * License Terms and Maps API Keys * Map View and Map Activity Classes * Configuring a Map * Controlling a Map * Events * Projections * Map Overlays * Item Overlays * Custom Overlays

Wednesday, March 13, 2013

Take (and Manipulate!) a Photo with a Web Page

So not that long ago, if you wanted an app to take a photo, it had to be a native app -- such as a Windows/Mac app or a native mobile application.  But HTML5 has brought a number of new APIs that allow not only taking photos, but analyzing and manipulating them all within a browser.

Sadly, there is still inconsistent support for these features across browsers (both desktop and mobile).  So in practice, the best approach may be to target the APIs supported by iOS 6, which is more or less the minimal feature set across browsers that support any of this at all.

The three pieces we'll need are:
  • The Canvas
  • File I/O
  • Changes to the File Upload input and Media Capture
    • Note that Media Capture has been superceded by getUserMedia (more info) but we don't use that here because iOS doesn't support getUserMedia yet

The Canvas is a space on the page to draw into, using either 2-D or 3-D APIs.  Conveniently, it also lets you draw images into it, inspect and alter the pixel data, and export its content as an image. Canvas is supported by IE 9 and modern versions of Firefox, WebKit/Safari/iOS 6, Opera, and Chrome.  However, not all browsers support 3-D (via WebGL), and browsers don't generally support ALL of the Canvas spec (which has continued to evolve even after initial browser support).  Still, the parts we need are supported across browsers.

The additional "accept" and "capture" attributes on the file upload input element let us specify that the user should be able to select an image file, getting it from an attached camera if possible.  Crucially, on iOS you are given the option to select a photo from the photo library or take a photo on the spot (though some desktop browsers only let you browse for an image file, even if a Webcam is attached). Then the "files" property on the input element lets us access the selected files (unfortunately, not supported in IE < 10).

So the formula for taking and manipulating a photo is:
  1. Configure a file input using the new attributes
  2. When an image file is selected (or photo taken), access the image file
  3. Check the image EXIF data for rotation using File I/O
  4. Decide what size to scale the image to (if needed)
  5. Configure a Canvas for the selected image dimensions
  6. Draw the image to the Canvas, rotating and scaling as appropriate
  7. Access and manipulate the pixel data for the Canvas
  8. Write the pixel data back to the Canvas
  9. Export the image on the Canvas as an image file

Taking these one step at a time (and note that I use jQuery for convenience, but it is not needed for this to work):

1. Configure a file input using the new attributes

There are two ways to configure the input (and it makes no difference to desktop browsers). An input configured like this will prompt the user to take a photo or select a saved impage on either iOS or Android:
<input type="file" id="PhotoPicker"
       accept="image/*" />
With the additional capture="camera" attribute, Android goes directly to the camera without giving the option to use a saved photo (though the iOS behavior is the same):
<input type="file" id="PhotoPicker"
       accept="image/*" capture="camera" />
Note that if you don't like the default appearance, you can conceal the input widget and connect a button or link (styled any way you like) to activate it.  The input doesn't work if set to display: 'none', but we can put it inside a div of size 0 to effectively hide it:
<div style="width: 0; height: 0; overflow: hidden;">
    <input type="file" id="PhotoPicker" 
           accept="image/*" capture="camera" />
</div>
<button class="lovely" id="PhotoButton">1. Select Photo</button>
$('#PhotoButton').click(function() {
    $('#PhotoPicker').trigger('click');
    return false;
});

2. When an image file is selected (or photo taken), access the image file

We just use the new files property on the input:
$('#PhotoPicker').on('change', function(e) {
    e.preventDefault();
    if(this.files.length === 0) return;
    var imageFile = this.files[0];
    ...
});

3. Check the image EXIF data for rotation using File I/O:

All images may have a rotation recorded by the camera, such that no matter how the camera was oriented when the photo was taken, the image can be displayed appropriately on screen.  In particular, an iPad considers the landscape orientation to be normal (though it can still be upside-down), and the portrait orientation takes photos with a 90 degree rotation.  The EXIF header in an image records this rotation, so we can read it in order to display the image appropriately.

This part uses two open source (MPL) EXIF-reading scripts:
<script src="http://www.nihilogic.dk/labs/exif/exif.js"
       type="text/javascript"></script>
<script src="http://www.nihilogic.dk/labs/binaryajax/binaryajax.js"
       type="text/javascript"></script>
Then we use the new File API to read the image data (and there's a nice image here describing the EXIF Orientation codes):
var width;
var height;
var binaryReader = new FileReader();
binaryReader.onloadend=function(d) {
    var exif, transform = "none";
    exif=EXIF.readFromBinaryFile(createBinaryFile(d.target.result));

    if(exif.Orientation === 8) {
        width = img.height;
        height = img.width;
        transform = "left";
    } else if(exif.Orientation === 6) {
        width = img.height;
        height = img.width;
        transform = "right";
    }
    ...
};

binaryReader.readAsArrayBuffer(imageFile);

4. Decide what size to scale the image to (if needed)

If you want to limit the size of the image, you can scale the height and width accordingly. With mobile devices with high-resolution cameras, this may be necessary to limit memory usage:
var MAX_WIDTH = 1024;
var MAX_HEIGHT = 768;
if (width/MAX_WIDTH > height/MAX_HEIGHT) {
    if (width > MAX_WIDTH) {
        height *= MAX_WIDTH / width;
        width = MAX_WIDTH;
    }
} else {
    if (height > MAX_HEIGHT) {
        width *= MAX_HEIGHT / height;
        height = MAX_HEIGHT;
    }
}

5. Configure a Canvas for the selected image dimensions

If the canvas is on the page, you can just grab it:
var canvas = $('#PhotoEdit')[0];
Otherwise, you can use an offscreen canvas:
var canvas = document.createElement('canvas');
And then size it accordingly:
canvas.width = width;
canvas.height = height;

6. Draw the image to the Canvas, rotating and scaling as appropriate

In order to draw the image to a Canvas, first we have to load it in an <img />, and a convenient way is to create a URL to assign as the img.src from the selected file (using part of the File API):
var img = new Image();
var url = window.URL ? window.URL : window.webkitURL;
img.src = url.createObjectURL(imageFile);
img.onload = function(e) {
    url.revokeObjectURL(this.src);
    ...
};
Then inside the onload handler, we can draw the image to the canvas. (In practice, I put most of the logic we're discussing inside the onload handler.) A transformation matrix on the context handles rotating the image (if needed) and shifting it back into the viewable area.
var ctx = canvas.getContext("2d");
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, 700, 600);
if(transform === 'left') {
    ctx.setTransform(0, -1, 1, 0, 0, height);
    ctx.drawImage(img, 0, 0, height, width);
} else if(transform === 'right') {
    ctx.setTransform(0, 1, -1, 0, width, 0);
    ctx.drawImage(img, 0, 0, height, width);
} else if(transform === 'flip') {
    ctx.setTransform(1, 0, 0, -1, 0, height);
    ctx.drawImage(img, 0, 0, width, height);
} else {
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.drawImage(img, 0, 0, width, height);
}
ctx.setTransform(1, 0, 0, 1, 0, 0);

7. Access and manipulate the pixel data for the Canvas

The getImageData method returns an array of pixel data, with one byte each for red, green, blue, and alpha. This example applies a "green screen" effect, setting pixels to transparent (alpha = 0) if they are mainly green.
var pixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
var r, g, b, i;
for (var py = 0; py < pixels.height; py += 1) {
    for (var px = 0; px < pixels.width; px += 1) {
        i = (py*pixels.width + px)*4;
        r = pixels.data[i];
        g = pixels.data[i+1];
        b = pixels.data[i+2];
        if(g > 100 && g > r*1.35 && g > b*1.6) pixels.data[i+3] = 0;
    }
}
There are of course other possibilities for filtering the image.

8. Write the pixel data back to the Canvas

Then we use putImageData to write the array of pixel data back to the canvas.
ctx.putImageData(pixels, 0, 0);

9. Export the image on the Canvas as an image file

Finally, the whole content of the canvas can be exported as an image. There may be a way to do this through the browser (in Firefox, for instance, right-clicking on any Canvas lets you view it as an image), but there is a canvas API call as well. Every browser supports saving the image as a PNG, and some may support other formats:
var data = canvas.toDataURL('image/png');
The resulting data URL looks like this:
data:image/png;base64,...
Where the "..." is the base 64 encoded version of the binary image file. So you can, for instance, upload the data URL to a server as a form field, and the server can strip off the data:image/png;base64, prefix and base 64 decode the rest and save it to a file like mycanvas.png.

Summary

So there you have it -- a Web page that takes a photograph, scales and orients it as appropriate, processes the image as desired, and then displays it to the user and/or uploads it to a server.
Unfortunately, there is not yet a way to present a "Save As" dialog to the user to save the file directly to their local disk -- the FileSystem and FileWriter APIs are not widely supported across browsers. But you can of course upload the image to the server and then redirect the user to a server URL to save it...

Consolidated Sample Code

Here's a single page with a working example using the code we've gone through here.

You can also use this sample image to see the green screen replacement effect.

Platform Support

Bold entries work fully:

Desktop Browsers:
  • Firefox 18
  • Safari 6
  • Chrome 25
  • IE 10
  • IE 9 (does not support getting selected files from file input)

Mobile Browsers:
  • iOS 6
  • iOS 5 (file input doesn't work)
  • BlackBerry 10
  • Android 4.1 (built-in browser)
  • Android 4.1 with Chrome from Play store
  • Android 2 (native browser; does not take photo)
  • Windows Phone 8 (file input doesn't work)
  • Surface RT (doesn't work)

Thursday, November 15, 2012

Installing PhoneGap Plugins with pluginstall

Phonegap applications can be extended with plugins to add additional functionality. Historically, installing plugins meant copying a bunch of files into the correct places in your project.

Andrew Lunny wrote the Cordova Plugin Specification and pluginstall. Pluginstall is a tool that automates the installation of plugins which conform to the plugin specification.

In addition to demonstrating pluginstall, we’ll also use the PhoneGap create script to make a new project. The cordova build scripts will be used for compiling and installing the binary. Using these tools it’s possible to develop PhoneGap apps with a text editor, instead of an IDE.

Prerequisites

I’ll assume that you have Phonegap 2.2.0 and the Android SDK installed.

Pluginstall requires node.js and is installed through npm. If you’re on a mac and use homebrew, install node and npm with brew install node.

Setup

Install pluginstall

$ npm install -g pluginstall

Create a new Android project using the PhoneGap create script. Create takes the new project path, package name and activity name as arguments.

$ cd /usr/local/phonegap-2.2.0/lib/android
$ ./bin/create ~/foo com.example.foo Foo

The create script built a new PhoneGap project in directory ~/foo. Inside the project there is a cordova directory with some command line tools.

Let’s ensure the generated project works before we modify anything. Start the emulator.

$ cd ~/foo
$ corodova/emulate

Patiently wait for the emulator to start. Unlock the screen and keep the emulator running. Compile, build, install, and launch your app.

$ cordova/BOOM

The application should launch and say “Device is ready”.

Install the plugin

Get a local copy of the Child Browser Plugin.

$ cd /tmp
$ git clone git://github.com/alunny/ChildBrowser.git

Install the plugin using pluginstall. Pluginstall takes the platform, project directory and plugin directory as arguments.

$ pluginstall android ~/foo /tmp/ChildBrowser

The Child Browser plugin is now installed. Pluginstall used to the information in the plugin.xml manifest to update the project. It added an Activity to the Android manifest, listed the plugin in config.xml, added java source code, and added javascript code and images to our project.

Write some code to use the plugin

Edit ~/foo/assets/www/index.html

Include the javascript after cordova.js

<script type="text/javascript" src="cordova-2.2.0.js"></script>
<script type="text/javascript" src="childbrowser.js"></script>
<script type="text/javascript" src="js/index.js"></script>

Edit ~/foo/assets/www/js/index.js

In onDeviceReady, add a call that will open a web page in the Child Browser after 3 seconds

onDeviceReady: function() {
    app.receivedEvent('deviceready');
    setTimeout( function() {
        window.plugins.childBrowser.showWebPage(
            'http://phonegap.com', { showLocationBar: true }
        );
    }, 3000 );        
},

Compile, build, install, and launch your app into the running emulator.

$ cordova/BOOM

The sample application should run and open http://phonegap.com in the Child Browser Plugin.

Monday, October 22, 2012

Top Questions To Ask When Choosing an Android Development Firm or Developer

Now that we understand the implications and challenges of embarking on an Android project, let's discuss how to find the right firm or developer for the job!

You are ultimately responsible for the application - even if you go the outsourcing route. Things happen, disagreements happen, and turn over happens. The likelihood is high that you will need to maintain the application at some point in its lifecycle. The better the code, the easier the maintenance will be.

There is a wide range of abilities, experience, and knowledge out there. These questions are designed to help you make the best choice about how to invest your Android budget. You need to ensure that anybody you onboard to build the application will advance your organization's goals and not cause unnecessary rework.

Interview Questions

  1. What applications have you published in the market? Do you have references we can contact? Describe application features and your role in each application.
  2. Do they speak positively of their clients and applications? What do their references have to say? How high are the app ratings? Take note of positive and negative comments. If possible, download and try the application(s). This will give you some insight into the quality of the implementation and design.

    Do they use similar platform features to what you plan to use? For example, have they only written map applications when you want to create a music streaming application? Keep in mind there is a plethora of platform features, so unfamiliarity with a particular feature isn't a deal breaker. Great engineers can pick up any new feature very quickly. If something is business critical and you are uncomfortable with them learning this for your application, you may want to look for someone with experience with these features.

  3. How do fragments fit into your development process?
  4. Any firm or developer you hire should be knowledgeable of fragments and should be using them. Otherwise, they are writing obsolete code. This technology is nearing two years old and is the way to write Android apps going forward. Frankly, if they haven't taken the time to learn them by now, how can you trust that they will help you innovate in your application?

    If they don't use them, you will need to completely renovate the application when you expand to the Android tablet market. On the other hand, if they write it with fragments from the start it will be much easier to transition to tablets.

    There is a large base of Android developers who remain resistant to learning this new and more flexible way to build applications. I've gone on a conference crusade this year to help businesses and developers see the benefits of switching to fragments before it's too late.

  5. What strategies do you use to ensure the user interface will scale to the multitude of Android devices?
  6. There are many strategies and best practices for making interfaces that scale. Some of the things you’ll want to hear from the developer or firm are:
    • Using fragments
    • Using dimensions, styles, and qualifiers
    • Using 9-patches
    • Using images in different densities
    • Wrapping elements and using relative layouts
    • Not using fixed pixels

  7. How do you minimize battery life drain and bandwidth usage?
  8. If they don't have ideas around this, beware. This is one of user’s main complaints! There is typically a cap on data plans, so users want to limit bandwidth so they don’t get hit with overages. Battery is also a major concern for users. A major factor in battery life is the amount of data downloaded and processed on the device.

    Some techniques are using services to complete background work, using alarms to kick of background tasks, detecting when on WiFi and downloading large amounts of data, designing APIs that give incremental data, or detecting when plugged into the wall to do a large amount of processing.

  9. Do you unit test your applications? Do you write integration or other automated tests?
  10. Test coverage is an important judge of quality for the end product. Although it seems like it's just more code to write, the investment up front will reduce bugs and rework. It may or may not speed time to market, but it will definitely increase the quality of your application.

    Developers that don't use unit testing spend a lot of time building to devices or emulators. This uses significant amounts of time that could be use for writing tests to verify behavior. Plus they won't be able to find all the bugs by poking around in the application.

    Although many Android developers eschew using testing frameworks like Robolectric, setting up new projects with Robolectric, IntelliJ, and maven (or maven + Eclipse) avoids the headaches that come from integrating later on in the project. There are many things you could test, but there are limits and tradeoffs. Check out my article about best practices for testing with Robolectric to help you structure your testing strategy.

    Although unit testing in great, there are other types of testing. The more types of tests that are written, the bigger safety net you have when the architecture needs to change. It will help ensure that large changes don't break existing functionality and find subtle bugs before they get into the wild.

  11. How often will we discuss and decide priorities?
  12. Priorities change - often quickly and without warning. You will encounter challenges even with the best thought out designs. Business requirements will change and it's essential to keep in close contact with your developers to make sure critical features are implemented according to the latest specifications.

  13. How will I access the code base?
  14. It's always a good idea to have access to the code. A good practice is to create an organization on github and invite the developer(s) to join your team. They create a repository for your application and save any changes in the cloud. This gives you access to the most updated code as well as the commit history. You can browse code commits to see what they are working on and get an idea of where the project stands.

    Although we always embark on new contracts with good will on both sides, disputes with an external firm or developer can happen. Make sure that you have access to and retain the rights of your application's code. You can't develop or maintain what you don't have!

  15. Will I get regular builds of the application?
  16. It's also possible to get frequent builds of the app - either manually or as part of an automatic process. Giving stakeholders access to regular builds is a good idea so that the business can ensure that the developers are creating the features as expected.
What has your experience been with hiring Android developers or firms? How did you determine their skill level? We'd love to hear about it in the comments.

Wednesday, September 26, 2012

So You Want To Build An Android App?

If you’re reading this, you likely have an iPhone/iPad (iOS) application and are interested in expanding to the Android platform. You've probably already asked the hard questions to define what you want, why you want it, and how it fits into your roadmap. This article will help your business understand the impact of the Android effort.

Android ≠ iOS

This should be obvious, but too often business think "I have an iOS app, how different can it be?" The challenges on each platform are not the same and some factors make Android applications a bit trickier to develop and maintain.

It is unrealistic to think that the exact time (or less) taken to build your iOS application can yield an Android app. The underlying assumption is that all the mobile problems were solved with the iOS effort and perfect conditions are now in place to start a new application. This thinking doesn't leave room to reevaluate infrastructure decisions that could impact the device or scale to new demands. It assumes that there are no developer or institutional knowledge gaps. Finally, it doesn't leave room evaluate the current set of features and how the design translates to the new platform.

Development & Testing

Android does not have a small subset of form factors and OS versions like the iOS ecosphere. There are a multitude of devices that officially (and unofficially) run the Android OS. The OS version distribution impacts both hardware and software features that you can leverage in your application. Also, there are many legacy phones still in use.

This increases complexity of creating an application that looks great on all devices. However, the Android platform has many ways to mitigate these challenges. It's critical to hire engineers and designers that have a good grasp of the platform so that you can reach a wide audience while preserving your brand.

Your organization should define a strategy around which devices to support (preferably when an Android expert is in the room). Different approaches come into play here, but a common one is to pick a representative sampling of devices and make sure the application works well on them. Whichever way you go, the decision will impact the level of testing and development effort.

This may seem daunting, but your application will have a much further reach - on everything from phones to televisions!

Design

There is tremendous value in making your users happy by giving them an intuitive and optimal user experience. This drives adoption and makes your users much more likely to continue to engage with your app over time.

You can’t simply take your current application’s look and feel and shoehorn it into an Android device. This is disrespectful to your users and makes it clear that you view Android as an afterthought. Navigation, user interactions, and widget standards are very different and should be respected on each platform.

It’s critical to evaluate your current features and determine how they will translate to the Android platform. The upside to this fresh perspective is that you will discover ways to leverage platform features that are unique to Android (e.g. rich notifications and widgets).
--
Bottom line: The design will be different, the code base will be different, and the challenges will be different. Make your users happy and follow Android design standards.

Are you building a team or an app?

Once an application is in the market, it will need care and feeding. There will be bug fixes and a growing list of new features to implement. The goal is to find an approach that fits into your mobile strategy and creates a sustainable process around the application. The main trade off is creating an organization in-house or using external firms. Let's look at both approaches in detail.

External team

Outsourcing could provide many advantages for your organization. Although consulting has a higher up front cost, you won't be paying to train and maintain a team. You pay-as-you-go and build only business critical features. The downside is that you’ll continue to pay the firm for maintenance, bug fixes, and feature growth.

Although it's tempting to think about this as something you can just hand off to another firm, you should be involved at all stages. Communication is key to making this approach successful because any external party won't understand your business as well as you do. Being involved in the design and feature prioritization process will ensure that the application created is what you envisioned. You don't want your app built in a vacuum and end up surprised by the end product!

There are several options, including hiring a contracting firm, a boutique firm, an independent contractor, or an overseas team. Contracting firms typically have several contractors that either create apps from scratch or embed with existing teams. Boutique shops have extensive experience with a particular platform and know how to best leverage its features. Independent contractors are typically self employed and work on several applications at once. Finally, you can hire an overseas team for cheaper than what you'd pay a local contractor.

Experience varies widely in the Android development realm. Make sure to ask the right technical questions (covered in detail in the next blog in the series) to ensure you are getting a high quality software product. Aggressively check references and contact past clients to gauge how happy they are with the end product. Install their published applications and check ratings and comments in the Google Play market. Finally, determine how maintainable and easy to extend the app will be (just in case you or someone else needs to update it).

In-house team

Creating a team internally makes sense for many businesses. It allows you to leverage your existing developers and have complete control over the roadmap. You won’t need to pay outside firms each time you want a new feature. Finally, you won’t have to manage the risk of having external developers create your app.

The drawback of this approach is creating and maintaining a team. It's a massive commitment and fiscal investment to support this team. You need to recruit, train, and have enough work for developers to do over the long haul. Depending on the scope of your application and your business objectives, creating your own team can be overkill.

Do you have the right knowledge to select developers to help you with this effort? There is no shortage of developers interested in switching to mobile development because it's an exciting corner of technology. However, it can be challenging to find the talent with the right experience. One strategy is to recruit internal developers and retrain them as mobile developers. Skills like Java and front-end development translate well to Android because it's written in a mixture of XML and Java. This technique is especially effective when combined with hiring an architect to help build the team.

Organizations tend to face the same challenges when beginning a team and an experienced architect can help you avoid these pitfalls. Team augmentation, which is hiring one or more experts to mentor new developers and increase the team Android knowledge, is one way to make this an easier process. Hiring this expert can help you get the right architecture in place, recruit new members, implement best practices, set up continuous integration, mentor team members, and inform the organization about the challenges and constraints of mobile development. Team augmentation can help you make a sustainable team much earlier. Plus there is an endpoint - you decide when to remove the training wheels.
--
Stay tuned for more articles in the series that will focus on choosing the best developers, designers, and testers for your Android project.

Tuesday, August 7, 2012

Android Unit Testing With Robolectric

Are you interested in adding Robolectric to your development process? Here's a quick introduction to the most common types of test cases and some best practices to consider when deciding your testing strategy.

I've created two example apps for your reference. The first is a glorified Hello World and the other is a simple animation app. If you are unfamiliar with Robolectric, I'd start with my introductory blog that details how to integrate IntelliJ, Robolectric, and Maven into your project.

What To Test

You should focus your unit testing on business logic, basic view validation, and functionality. You can validate certain requirements very well with unit testing (e.g. "when I click this bell image, it whistles" or "all activities have a logo on the screen").

Here are some common examples:
  • Ensure the activity and view elements are not null.
  • Ensure expected view elements are visibile on the screen.
  • Ensure that the proper resources are used for view elements.
  • Ensure items are hidden when expected.
  • Ensure that your intent starts the correct thing.
  • Ensure that fragments are present.

What Not To Test

I don't recommend investing much time in verifying less important styling details and XML attributes. Your user interface is likely to change many times a week, but typically the basic view elements and their behavior remain the same. If you updated a test each time a button had new padding, that would get very tedious indeed!

Example: The app logo is 250dp high with a proportional width, the file name is "main_logo.png", it has a 20dp left margin and 12dp right margin, has a content description of "Text," and is centered vertically on every screen.

You are likely able to test all of the attributes above (I haven't tried), but your time is best spent on items that are most important to the business. From this example, likely the most bang for your buck will come from testing that the proper image is used and making sure that it appears on all expected screens.

Returns start diminishing pretty quickly when you verify every possible XML attribute - unless that detail has an important business outcome for your app. Many of the attributes you don't test can be caught by designers, quality assurance, business, product, and/or the engineers. A better stategy is to sweep the app near deployment with a designer to make sure the app appears as expected on a wide range of devices.

Best Practices

  • Simplify your architecture. As with most object oriented realms, attempt to simplify the architecture as much as possible. Do this by creating abstract or base objects or interfaces. This way you can test shared behavior in one place instead of several, which simplifies tests and reduces code duplication.
  • Mock/stub functionality. Often we want to ensure that a certain action was performed but not actually run the code. To do this, you create a test class which extends the class under test and override/mock out/track that a particular function was called. For example, if you want a particular click to make an API call, there is no need to make the actual call (since this would be an integration level test). You can use this strategy to track that the function that invokes the call has been called, but avoid making the actual call. This is also helpful when an operation crashes the unit testing framework (e.g. specialty library that causes funky side effects), doesn't play nice, or is otherwise unnecessary to invoke directly.
  • Create a custom test runner. Create a helper test runner to gives your entire unit test suite access to handy functionality. My simplest version includes string, drawable, and color resource fetching as well as view visibility helper functions. I also add a helper function to start fragments without a hosting activity. Finally, this is a good place to bind custom shadows you create and set up any external library configurations that you may need.
  • Centralize test constants. Android strongly encourages the use of abstracting string resources into one place over using hard-coded string constants. Use a test constants class when you have lots of test data (e.g. When creating a user with lots of fields to mock out a JSON response).
  • Have a robust testing strategy. Don't rely solely on unit tests to ensure the proper implementation of your app. These tests, though quite useful, only give you a small window into your app and it's behavior. At minimum, you should include integration level tests and have some level of manual QA in the process to ensure your app is everything that you want it to be.

Notes

  • Unit testing Android apps is not as simple as with other platforms and Robolectric is still a work in progress. You will find things that you'd like to test that the library doesn't suport. It's up to your organization to determine how much they would like to invest to give back the the community by writing and fleshing out shadow classes.
  • When running the sample tests you may notice a few warnings about binding map-related shadow classes (because the library is not available in the maven central repository). To solve this issue use the maven android SDK deployer.
    Warning: an error occurred while binding shadow class: ShadowGeoPoint
    Warning: an error occurred while binding shadow class: ShadowItemizedOverlay
    Warning: an error occurred while binding shadow class: ShadowMapController
    Warning: an error occurred while binding shadow class: ShadowMapActivity
    Warning: an error occurred while binding shadow class: ShadowMapView
    Warning: an error occurred while binding shadow class: ShadowOverlayItem
I hope you found this blog useful for getting started with Robolectric! If you are already using it, what do you find most useful or helpful? How does it fit into your testing strategy?

Friday, August 3, 2012

Integrating Robolectric with IntelliJ

Unit testing is a best practice, but has been particularly difficult in Android. One library that makes this process much simpler is Robolectric. Integration into your project can be tricky and most methods start with maven and create an Android project from scratch.

I'm a huge fan of living in IDE-land as much as possible, so this approach minimizes command line work and manual project configuration. This tutorial will walk you through using IntelliJ to generate the project and maven integration to make installation of Robolectric simpler.
After creating an Android project with the wizard, you move the source files into a mvn-like structure. Then you configure module settings in IntelliJ. To install Robolectric, you will add a pom file (maven dependency file) into the project. Finally, you will write your first test and run it inside the IDE.

Note: There are other projects and methods out there, but this is what I found to be the most effective way to get up and running. If you'd prefer an all in one solution, check out this project.

Assumptions:

  • You are starting a new project.
  • You are familiar with the IntelliJ and the Android wizard (CE edition is fine).
  • You have installed the Android SDK and configured IntelliJ to use it.
  • You have maven installed.

Step 1: Create Android project using IntelliJ wizard

Use the IntelliJ Android wizard to create a Hello World project.

Step 2: Set up directories for maven

Use IntelliJ or the command line to move files into the following structure:

src/main/java/com/...
src/test/java/com/...

After you are done, your project should look something like this (minus the test files):
Note: IntelliJ might not like it when you add subdirectories to the folder marked as source. If you are having trouble setting up the directory structure, open the screen shown in the next step and remove the old source folder before adding new subfolders.

Step 3: Configure IntelliJ source and test folders

Update module settings in IntelliJ to recognize the source and test directories (below: blue folder is source and test folder is green).


Step 4: Install Robolectric

Use this sample pom.xml to get you started. Change the groupId, artifactId, version, and name tags to suit your project. The file should live in the root of the project.
And some of my environment set up (zsh):
# Shell Settings (one long line, broken for view online)
export ANDROID_HOME="/usr/bin/android-sdk-macosx"
export PATH="/usr/bin/android-sdk-macosx/platform-tools:/usr/bin:
             /usr/bin/android-sdk-macosx/tools:
             /usr/local/apache-maven-2.1.2/bin:$PATH"
After updating the pom and environment variables, check the project in IntelliJ to make sure the "Maven Projects" view looks something like this (you may need to refresh):


If you see errors, you may just need to wait for it to finish indexing and importing your libraries. If you have git configured, once you see this dialog, you should be moments away from running your first test.

Step 5: Create test

I use the IDE to generate a test. On a Mac, the key combination is Apple+Shift+T.

Step 6: Write test & run

Right click on the test file name to run the test or use keyboard shortcut. TODO - resolve - If you are seeing issues similar to this, rebuild your project a few times to convince IntelliJ to generate the R.java file (which links to all your applications resources) and/or run "mvn install" from the command line.

If you are still having issues, update your Android facet here:
Success!

Optional Step 7: Create a run config for all tests

You could run each test individually as you work with new classes, however it should be a common task to run all the unit tests (e.g. prior to commit). I create a run configuration for the whole project:  


Next Steps

Now that you've got it integrated into your project, why not try adding a few tests? Check out the next blog in the series that shows you how to write test for your project.

Friday, May 25, 2012

Read and Write NFC Tags with PhoneGap

The phonegap-nfc plugin allows you to read and write NFC tags from a PhoneGap application using JavaScript.

The plugin originally supported Android. The latest release adds support for Blackberry 7.0.

After installing the plugin into your PhoneGap app (See README) it is easy to start scanning tags.

Create a function that will handle the NFC events.

function onNfc(nfcEvent) {
    // display the tag as JSON
    alert(JSON.stringify(nfcEvent.tag));
}

Create the optional success and failure callbacks. These callbacks are for success and failure of adding the listener.

function success(result) {
    console.log("Listening for NFC Messages");
}

function failure(reason) {
    alert("Failed to add NDEF listener");
}

Register listener. When the listener is added, the plugin will generate an NFC Event whenever a tag is scanned.

nfc.addNdefListener(onNfc, success, failure);

Deploy the application and scan a tag.

Example Project

The NFC Reader example project has been updated for Blackberry.

More info

The PhoneGap NFC API is documented in the README file.

Kevin wrote Building NFC applications with Android last year. Most of that information still applies.

Friday, May 4, 2012

Camera Access from Android Browser

The browser in Android 4 is able to take pictures from a web page and display them without any plugins or server interaction. This demo uses the Device API and File API to take and display a picture on a phone using the browser.

Try it on your Android phone http://don.github.com/html-cam/.

I wrote this demo after reading David Calhoun’s post about Android implementing device APIs.

This works on my Google Nexus S running Ice Cream Sandwich (4.0.4). The Device API works on Samsung Galaxy Tab 10.1 with Honeycomb (3.2) but the File APIs do not. YMMV.

Loading images from the gallery is finicky. Images load from the device but fail to load from Picasa albums. I had to alter the image blob and change data:base64 to data:image/jpeg;base64 to get photos from galleries to display.

I kludge the photo orientation based on the device orientation, clearly there is a better solution.

It's possible to run the browser out of memory. I'm guessing this is because a huge photo is encoded into a base64 string. Maybe window.URL.createObjectURL(file) would work better than reading the image with FileReader?

Adjusting the input tag can control the input types:

<input type="file" />
Browser prompts for camera, camcorder, sound recorder, 
  music track, or gallery

<input type="file" accept="image/*" />          
Browser prompts for camera or gallery   

<input type="file" accept="image/*;capture=camera" />           
Browser goes directly to the camera

For more info see the github project.

UPDATE 2012-05-06
It looks like Facebook's mobile website allows camera access from a browser on Android.

Friday, March 2, 2012

Android 101: A Crash Course

Tomorrow is Chariot Day! Charioteers will give 45 minute presentations on a broad spectrum of topics, including enterprise Java techniques, mobile, and Arduinos.

I'm planning a dive into Android and teaching concepts along the way. At the end of my session, students will away with a simple Doctor Who app and learn about these foundation topics:
  • XML layouts
  • Themes, styles, drawables, & strings
  • Click/event handling
  • Starting a new activity
  • Specifying an icon for the app
  • Fragments & tablet version (if time)
Read more here!

Friday, February 4, 2011

Philly ETE 2011 mobile line up!


 This post is via Kevin Griffin, Chariot Architect and committee chair of the Mobile tract for ETE:

 Philly ETE 2011 mobile line up!

Just thought I would post an update on the current lineup for Philly ETE.
I've been involved in helping get the mobile track lineup sorted out and so far we have confirmed the following:
  • Josh Clark - my favorite 'Tapworthy' author.
  • Johnathon Stark - He literally wrote the books on making mobile apps with HTML, CSS and JavaScript.
  • Ted Neward - If you are lazy, and want to write Android apps, he has the talk for you!
  • Jay McGavren - If you want to write Android apps, in Ruby (Oh yeah!) This is the talk for you (personally, I can't wait for this one!).
  • Terry Ryan - Philly Evangelist from Adobe who will use Air, to build Playbook apps. Magic!
  • David Kaneda - Although technically on the Frameworks track. Go build your mobile apps in Sencha Touch, seriously go now! That way you can thank him at ETE!
With one super secret invite still pending :D

Tuesday, November 16, 2010

NFC. What does it all mean?

NFC: Near Field Communications: a short-range high frequency wireless communication technology which enables the exchange of data between devices over about a 10 centimeter (around 4 inches) distance (via Wikipedia).

Well that's great, but what does it mean, especially when mentioned in conjunction with Gingerbread?

As you may (or may not) have heard this week at the Web2.0 Summit Eric Schmidt talk about Android 2.3 and its support for NFC. This could indeed lead the way for mobile payments on devices. NFC will allow for the transmission of credit card data over a defined radio frequency (13.56 MHz).

This isn't new, Japanese handsets (Keitai) have had this type of technology for a while (I want to say up to 10 years, but I can't back that up right now). Go google Osaifu-Keitai/keitai credit.

However this *is* all exciting news. There is potential for integrating it with conferences, museums, travel, healthcare, payment systems, and countless other things. Lets not forget though, some of these things already exist already:

  • Exxon SpeedPass
  • Debit cards with Visa PayWave.

Now we have another new way to gain information about our surroundings. #mobilefirst anyone?

Some interesting articles to peruse at your leisure.

RFID in Museums - Another Growing Market

Who Will Win the Mobile Payments Battle: Gadgets, NFC or Apps?

Intuit Squares Off In Mobile Credit, With A Little Help From Apple

Future Credit Cards: Electronic and RFID?

Web 2.0 Summit 2010: Eric Schmidt, "A Conversation with Eric Schmidt"

Wednesday, November 10, 2010

Post Presentation Thoughts from our Mobile Seminar

Kevin Griffin was one of the presenters at our first Mobile Seminar Breakfast. Below is a recap of his thoughts after he finished his presentation.


Yesterday I presented at the first in a series of events for Chariot Solutions, the topic was 'Mobile Design Concepts'.

My goal was to try present things that I had learned/seen/been shown/done over the last couple of years, and try to get the audience out of the 'desktop browser' mind set when developing for mobile.

I drew from a lot of people that I have seen/meet including Luke Wroblewski (@LukeW), Josh Clark/Tapworthy (@globalmoxie), Mike Lee (@bmf) William Van Hecke (@fetjuel) and Brian Fling's book 'Mobile Design and Development' which I still think is the first book anyone planning on a mobile project should read. I was probably influenced by many more folks than that, but they are the obvious ones to me at the time of writing.

Cont. reading..

Thursday, July 1, 2010

Mobile Musings from June

June has been a busy month for mobile, primarily because of Apple's launch of iOS4 and the new iPhone (antenna woes and all). However, presenting an update on that would be too easy; here are a few things you might have missed in all the hubbub.

CNET reported that merely weeks after Microsoft launch of Kin, they would be stopping development, and focusing on Windows Phone 7. 1

Android released 2.2 to developers with the notable additions being:
  • Improved performance
  • Use as a portable hotspot (certain devices)
  • Exchange support
  • Multiple keyboard languages 2
Rhodes 2.0 was launched under its new MIT license allowing developers far more flexibility and a broader scope to use Rhodes in developing applications. RhoSync remained under Rhomobile commercial license. The launch of Rhodes 2.0 brought with it some new features, primarily the metadata framework, which I have yet to get my teeth into.3

MeeGo, the joint venture between Intel's Moblin and Nokia's Meamo announced its "Handset Project Day 1" complete with video (http://www.youtube.com/watch?v=EW5wpg5epMs), which I thought looked pretty darn slick. 4

I'll be keeping a closer eye on MeeGo as its growth continues, and looking out for new Intel Atom-based devices, until then though; I'll just have to hope Santa comes early with a new Aava smartphone for me :)

Tuesday, March 9, 2010

Rapid Mobile Application Prototyping with PhoneGap

There is no doubt that carving out a mobile presence is a priority for many companies offering any type of product or service, or for start ups looking to gain rapid exposure. The Apple App Store has over 100,000 apps on it, and the Android platform is gaining ground. Those are just the cool kids – let's not forget the grandfather of mobile technology, Blackberry. Others in the class include Palm, Symbian and of course, Windows.

Multiple Platforms
With so many platforms available there is a risk of losing focus on developing and producing applications as resources are expended on supporting multiple platforms – a necessary evil as each presents different development environments and eccentricities.
This is why PhoneGap really stands out at the moment as four [1] of the aforementioned platforms share a common factor – a WebKit-based browser. This doesn't include BlackBerry's announcement [2] of their new WebKit based browser to come in late 2010, which takes us to five out of the six platforms.

Enter PhoneGap
Where does PhoneGap sit in this picture? Well, it jumps off the canvas and sits in your lap! PhoneGap allows you to develop applications using HTML, CSS and JavaScript and provides a JavaScript API which enables you to interact with a device's native functionality [3]. In addition to this simple application architecture, PhoneGap comes with build scripts/plugins (PhoneGap extension for XCode) which bundle up your pages into a deployable application.
The packaging and deployment to device for iPhone, Android and Palm was trivial; I can only speculate that the remaining platforms are equally easy to deploy. In light of recent Apple 'crackdowns', as of October 7th [4], 2009, it is worth noting that PhoneGap (version 0.8.0 and higher) is Apple approved.

The JavaScript advantage?
Anyone who has used a JavaScript library, Prototype, jQuery, MooTools etc, knows how powerful they can be. Anyone who has not used them can easily pick up JavaScript basics. The guys over at PhoneGap recommend using XUIJS[5] with PhoneGap as it does not contain a lot of cross-browser compatibility overhead and weighs in at < 10kb compared with jQuery at 24kb – although for simple functionality you may want to avoid using a extra library at all.
Due to the fact that we are ultimately aiming to work inside one browser implementation (WebKit), we are not held hostage by the browser compatibility issues that have haunted JavaScript for so many years. That's not to say that fragmentation in the mobile world is not an issue [6].

Now, I am not going to try to argue that these HTML/JavaScript apps offer greater performance or a better user experience over their native counterparts. However, I will say that PhoneGap will allow the rapid development of an application for multiple platforms, using a single code base [7]. This is ideal for prototyping or for apps that will have a limited life span and do not warrant the time and investment of producing native apps.Considering all of this in combination with developments coming down the pipeline, most specifically HTML5 (which includes WebSockets and Client-side database storage), the potential for these types of mobile applications is vast and genuinely exciting.[1] Android, iPhone (safari), Palm (WebOS) Symbian/S60(WRT) http://en.wikipedia.org/wiki/List_of_web_browsers#WebKit-based_browsers

[2]http://devblog.blackberry.com/2010/02/blackberry-webkit-browser-preview-at-mobile-world-congress/

[3]http://nachbaur.com/blog/phonegap-officially-permitted-on-the-app-store

[4]Checkout the road map for specifics: http://phonegap.pbworks.com/Roadmap

[5]http://code.google.com/p/xui-js/

[6]http://techcrunch.com/2010/03/04/mobile-fragmentation-forever/

[7]ok, you are going to have to tweak it for BlackBerry.

Wednesday, February 17, 2010

Mobile Platforms - Interview with Roy Rosin and Rick Rasansky

I am a little behind on editing a backlog of videos. As I continue to learn how to edit and not become frustrated with iMovie (why is it Apple can create so many great, intuitive products, yet this one is difficult to use! That will be another blog post for another time!)

This interview took place a few weeks ago, but it seems to be more relevant now with the release of Windows Mobile. I sat down with Rick Rasansky and Roy Rosin at their offices to discuss why it is important to be paying attention to mobile development. Since both of these gentleman have been in the mobile space since early on, they have a lot of experience to draw on.



Rick and Roy will be part of a panel at the Emerging Technologies for the Enterprise Conference (www.phillyemergingtech.com) on April 8th. They are part of a management track which is addressing different Buzz word topics (cloud, social media, mobile). The goal is to help managers have good, non-vendor driven information in their arsenal to guide their choices in 2010.

Thursday, October 15, 2009

Getting Started with Android

Today, I interviewed Andy Oswald, one of our architects. Andy is embarking on developing an Android application for the Philly ETE conference.

In this talk, he discusses the choices he made in getting started. With so much information, he shows the particular path he took which may help if you are beginning this type of work.



The site he references is actually : developer.android.com

In future weeks, we'll follow Andy's progress as he finishes the application.