Android Activity Lifecycle Methods Typical Uses

Understanding the uses of the various Android Activity Lifecycle methods can be a bit tricky.  That is, knowing what do do when.  The chart below shows some typical uses for each of the callback methods.  The chart of from the video training course Learning Android App Programming.

A convenient way to remember the structure of the Activity callback methods is to think of when they're called relative to when the Activity is running:

  • onCreate()   (the only Activity method that must be implemented)
  • onStart()
  • onRestart()
  • onResume()
  • --------------- Activity running
  • onPause()
  • onStop()
  • onDestroy()

Actions taken in the callback methods often relate to the resources they're effecting. Resources that are typically more time consuming to establish, restore or eliminate are dealt with further from when the Activity is running. Conversely, resources that are less time consuming are dealt with closer to when the Activity is running. Here are some examples:

  • --------------- Activity running
  • Variables
  • Preferences
  • Animations
  • Broadcast Receivers
  • Server Connections
  • Databases
  • Background Threads
  • --------------- Activity shut down

 

Android User Interaction Through Listeners and Toasts

​Every Android App interacts with its users.  There are lot's of ways to implement this interaction, but two basic capabilities are listeners and toasts.

Click here to see a video from Learning Android App Programming demonstrating a Listener and Toast to give you a basic understanding of these important and useful techniques.

Android Development Using API Demos

Google provides API Demos apps for various releases of the Android system.  These apps contain hundreds of demos of Android capabilities.  They demonstrate the use of tens of thousands of lines of code and can be a big help to developers as they create their own apps.

However, the API Demos apps are not well documented and it can be difficult to find the code within them for a given function.  In authoring a recently released video tutorial course for Android Developers, I addressed this issue by creating an Excel worksheet that gives developers a tool to better understand the structure of the API Demos and to search the demos based on keywords to find the code they need.

A video explaining the use of API Demos is below...

Describes how to use Android API Demos. From the course Learning Android App Programming published by InfiniteSkills. More information is available at http://donkcowan.com/android-development-course/

Using Randomized Variable Values to Enhance HTML5 Canvas Animations

The HTML5 Canvas feature is bringing additional animation power to web pages.​  HTML5 Canvas allows web developers to embed sophisticated bit map animated graphics directly into web pages. 

In developing examples for my book on HTML5 Canvas (HTML5 Canvas for Dummies)​ I experimented with using randomized variable values to improve the realism of an animated fireworks display. I used random values within specified ranges for parameters such as fireworks colors, number of exploding particles, trajectory of particles, lifespan of particles and flight trajectories. I found that adding well constructed values (not too much or too little randomization) significantly increased the realism and appeal of the results.  Here's one example from the Fireworks app of setting a randomized value:​

     part[newPart].life = lifeMin +(Math.random()*(lifeMax-lifeMin));

See what you think ... click here to see it in action.

HTML5 vs. Native App Development

As you're likely aware, there's a big debate going on about whether HTML5 web sites are a better platform for mobile apps than native code development using Android, iOS and Windows.

The main selling point for HTML5 is the write-once-run-anywhere advantage. Web browsers on mobile devices can access web sites from any mobile platform. HTML5 is providing features that allow web page JavaScript code to access phone features like devices sensors and geo positioning. In theory, a well constructed HTML5 web page will look and perform like a mobile device native code app.

However, currently not all device features are available to HTML5 JavaScript code and native code apps have a performance advantage over HTML5 web pages viewed using a browser. Native code apps are presently the dominant choice among developers.

In HTML5's corner, though, the technology is improving and web browsers are ramping up their implementation of HTML5 features. Life would certainly be simpler for mobile developers if they could develop for only one platform, HTML5, instead of multiple native platforms.

Longer term, HTML5 will certainly continue to get better. But so will native platforms. In fact, native platforms may improve more rapidly than HTML5. HTML5 is a global standard developed by the W3C. It takes years of effort to change the standard and have these changes adopted by the various browsers. The individual native platforms (Android, iOS, Windows) can change as quickly as their developers (Google, Apple and Microsoft) want them to. So will HTML5 ever catch up?

Maybe not. Google, Apple and Microsoft have lots of developers and big budgets. They want their products to be competitive ... and that means constant improvements.

So, what's likely to happen? In my opinion, we'll have a blend of the two. In fact, this is taking place today. Native code platforms have Application Programming Interfaces (APIs) that support displaying web pages from within native code apps. Developers can use native code for what it does best and HTML5 web pages for what they do best. The exact mix will shift over time as all the platforms change and improve. 

For developers, this means that separate native code platforms will likely continue to exist. Write-once-run-anywhere will remain an elusive goal probably not realized for a long time, if ever. This doesn't mean that development costs can't be managed or reduced. HTML5 web pages can be developed and used by native code apps where appropriate. Functions specific to those pages can be write-once-run-anywhere. This may not be an optimal solution, but it's the game on the ground.

Smartphone Website with Laptop 2.png

WebPlatform.org: A Resource for Web Development

WebPlatform.org is a new organization and collection of websites that will provide open source resources for web development. It will cover topics such as HTML5, Canvas, SVG, Video, Animations, IndexedDB, CSS, WebGL, Transforms, Audio, Media Queries and FileAPI.

Bridge Design Pattern

This entry is part of a series on programming Design Patterns that provides a framework for the rapid recall and use of patterns during application design. 

The Bridge design pattern is used to define multiple processes that work on multiple object types with similar aspects.

To understand how this pattern might be used, consider how software to control a real bridge might be constructed. Such an application would have two processes: trafficControl() and gateControl() which would control two types of objects: cars and boats. 

      class Bridge - contains methods to control bridge activities.

          trafficControl(trafficType) - method that controls traffic signals.

            gateControl(trafficType) - method that controls the bridge gates.

      class Traffic - contains objects describing types of traffic.

            cars() - defines car objects

            boats() - defines boat objects

Adapter Design Pattern

This entry is part of a series on programming Design Patterns that provides a framework for the rapid recall and use of patterns during application design. 

The Adapter design pattern is used to wrap a class in code that allows that class to be used via a different interface. Another name for the pattern is a Wrapper.

To understand how this pattern might be used, consider how software to display an image on a fixed size device might be constructed. Assume the following class and method are provided by the standard device software:

class Display - contains methods to create displays on the device.

displayImage(source) - method that displays an image with the dimensions of the device screen.

An adapter would fit an image of any size to the device screen:

class DisplayAdapter - contains methods that fit an image of any size to the device screen.

imageAdapter(original) - method that changes the size of the original image to fit the display screen.

imageResample(original, resized) - method that resamples the image for size change.

displayImage(resized) - uses the method built into the device to display the resized image.

Which is the Best Browser

An analysis of Internet browsers by Top Ten Reviews places Google Chrome at the head of the list. The analysis shows, however, that it's a real horse race between the top five: Chrome, Firefox, Internet Explorer, Opera and Safari. Here are some of my observations based on this analysis and personal tests and experience:

Change after new releases: All of the browser developers are working hard to improve their products. With each new browser version release, the competitive landscape can change. For example, Internet Explorer had recently lagged in speed due to the lack of graphics hardware acceleration. Based on my tests, they're now the fastest running HTML5 Canvas animations.

Graphics hardware acceleration: GPU (Graphics Processing Unit) hardware acceleration is an important factor in browser speed. A browser displaying video or animation with GPU acceleration will outperform a browser without it by a factor of 3-4. That's right, 300-400%. A computer using just the CPU to manipulate graphics displays simply can't keep up with one using the combination of CPU and GPU. Hardware acceleration is a fairly complex topic. Basically, the browser offloads calculations from the CPU to the GPU. If you're interesting in some of the details, take a look at this discussion of hardware acceleration from the Chromium Projects.

Mobile lags desktop: Especially in speed, the mobile browsers lag desktop versions. Mobile devices simply don't have the computing power to match desktop devices. 

HTML5 Status

HTML5 Logo.png

The World Wide Web Consortium (W3C) has announced that a final recommendation for HTML 5.0 will be released in the 4th quarter of 2014. In spite of the "recommendation" terminology that W3C uses, this is official release of HTML5. This is a big deal and great news. Browser developers will have a firm definition of HTML5 they can use to bring their products up to a complete level of support for this latest version of HTML.

W3C has also defined the follow-on version, HTML 5.1, to be released in the 4th quarter of 2016. This release will include features that have been pushed out in order to get release 5.0 completed in 2014. Without this stragegy, W3C was looking at an indefinite specification development timeframe. 

Browser developers are not waiting for 2014 to begin implementation of HTML5. You can use www.html5test.com to check the status of your browser to see which features are supported and www.caniuse.com for a summary of the status of support by all the major browsers.

Software Application Re-use

Software re-use has gained popularity and success due to technologies like Object Oriented Programming. Software classes and methods can be re-used based on their documented parameters and functionality.

The emergence of mobile apps over the last few years offers another level of re-use, that of whole applications. Instead of re-developing the functionality of an app (e.g. Google Maps) the app can be invoked by passing control to the app, providing it with a valid input (e.g. an address.)

Marketimpacts.com developed a series of Android apps based on applicaiton re-use. The Quickclick Locale series of apps uses the Google Maps API to map the locations of various types of places such as ATMs, Restaurants and Shops. The value added by Quickclick is an easy to use front end and app icons for different types of places.

To our surprise, there seems to be some resistance from other developers to app re-use. The only negative comments the Quickclick apps have received complain that the app is passing control to Google Maps to do the mapping.  Certainly, we could have created our own maps. But why? Are we really smart enough to out-develop Google? Would we really want to scramble to update our apps with new mapping capabilities to match Google? We think not. Google themselves promotes the idea of app re-use.

App re-use has some powerful advantages:

Lowered development costs: App functionality can be had for the cost of implementing a siimple interface to the app to be re-used.

Automatic upgrades: When the app you're re-using is upgraded, your app automatically benefits.

Higher quality: It's unlikely you'll be able to duplicate all the functionality of an existing app focused on a specific niche.

Leverage of user knowledge: If the app you're re-using is popular, many users will already know how to use it. This is certainly the case with Google Maps.

Access to complete app functionality: Some apps, including Google Maps, provide only limited functionality via an API (Application Programming Interface). By passing control to and re-using the entire app, your users gain access to full functionality.

Code Comments

What makes good code comments? Should they be terse or expansive? Should they be frequent or used sparingly? Opinions on these and other aspects of code commenting vary widely. My take is this ... to answer these questions, start with the objectives for code comments:

To assist in development: Comments aid in understand functionality being implemented in code. For example, they can be used as pseudo-code place holders for eventual real code.

To speed development and maintenance: Comments allow more rapid digestion of code sections. This is especially important when revisiting code not recently seen or code developed by others.

To clarify code: The function of a section of even well constructed code may not be evident. Comments can add that critical piece of missing information.

Given these objectives, here are some suggestions:

Comment appropriate groups of code: Sometimes a single line of code might need explanation. Or there might be a long section of code that repeats similar functionality and a single comment will suffice for the group. It's a judgment call.

Leave signposts for developers: Even if a section of code can be understood without a comment, how long will it take for you, or someone else, to understand it after time passes? Also, it's sometimes important to be able to understand the flow of a function or application without necessarily understanding all the details. Give yourself and others a break, make understanding as easy as possible. Most code is not a programming quiz.

Clean up comments: Keep them up to date and free of extraneous information. Remove temporary words used during development. Make them understandable. After all, that's their purpose in life.

Add comments while coding: It's tempting to think you can go back later and add a comment to some code that looks perfectly clear to you as you write it. Don't do it. Leverage the knowledge you have in that temporary cache in your brain.

Use a fairly uniform comment style: You don't have to be perfectly uniform, but it's a good idea to used some consistency within an application. It helps with understanding and looks more professional. 

Add value to the code being commented: Don't just repeat what the code obviously tells you. Make the comment compliment and add value to the code.

CCM Code.jpg

What is HTML5 Canvas?

The Canvas feature of HTML5 is one of the most exciting new developments in web based capabilities in many years. Here are some key aspects:

HTML5 - Canvas is a part of the latest revision and improvement of the previous version (HTML4, released in the late 1990's) markup language for displaying web pages on the Internet.

Canvas Tag - The <canvas> tag joins the other HTML tags (there are around 100 now) as a way to include single or multiple Canvas areas on a web  page. 

Bit Map DisplayThe Canvas area you define with a <canvas> tag is a bit map display. You can manipulate individual pixels to draw objects, images, animations and video.

JavaScript ControlThe JavaScript language is used to control what is seen on the Canvas. The JavaScript application code is placed between the <head></head> and <script></script> tags of the web page.

Browser Based - The computing needed to create a Canvas display is done within the browser. In other words, it's client based, not server based. The means that creating a Canvas application is simpler than one requiring server based programming. It also means that the computing power needed to generate the Canvas display is not concentrated in single servers. Each user's browser handles its own work.

Animation - Canvas applications can generate animations. This is accomplished using callbacks from the browser. The Canvas application designates one of its functions to be called from the browser at specified time intervals. During each of these callbacks, the application draws a new Canvas display, moving objects slightly. When viewed as a continuous flow of Canvas displays, an animation is generated.

Audio/Video - Audio and video can be incorporated into your Canvas applications. Moving objects can create sounds and video images can be melded into other application objects. This is done without the use of any audio or video plugins.

Gaming - Game developers have all to tools necessary to create compelling HTML5 Canvas games.

Fun - Putting aside the technical aspects of Canvas ... it can be described as just plain fun. An HTML5 Canvas is a place where as a developer you can express your creative energies and as a user you can have expanded and enjoyable experiences.

For a more details look at HTML5 Canvas, watch for my upcoming book: HTML5 Canvas for Dummies.

Integrating Audio with HTML5 Canvas

One of the useful features of HTML5 Canvas is the ability to integrate audio, either with or without an audio player. Click here or on the image to see if it works on your browser ... click on my dog Daisy and/or the pelican to test simultaneous sounds.

When the new browser window opens, you can view the page source to see the code that generates the Canvas display.

This is one of the sample applications from HTML5 Canvas for Dummies.

HTML5 Canvas on a Smartphone

HTML5 Canvas is a highly anticipated feature that allows web developers to create sophisticated graphics on their website pages. Most desktop and laptop browsers now support the Canvas feature. Mobile browsers are catching up. To see if your browser supports Canvas, you can access www.html5test.com for an analysis and rating of your browser.  Also, give this Canvas app a try:

Managing Android Devices

Google has quite a task ... to manage an installed base of over a thousand different types of Android devices. Multiple sizes, shapes, features, etc. The positive way to describe this is variety. On the other hand, it has also been refered to as fragmentation.

So how do they do it? In short, leverage. A good metaphor is a mechanical shovel. Relatively compact machines can move and lift very heavy objects using a system of joints and lever articulation. Android does something similar.

The code in Android applications doesn't manipulate devices directly. There are intermediate joints and levers that make the task manageable. Application code is programmed using component names to refer to layout elements. Layouts are adjusted to device characteristics automatically by the Android operating system. This lets an individual line of code manipulate many different types of devices.

This is a simplified view of how it all happens. There are a number of Android features that make it work: Themes, Styles, Action Bars, Fragments, Resources and much more. When implemented properly, an Android application can move a thousand different types of devices.

Coding for Better Understanding

A recent article in the Communications of the ACM focuses on how to improve the understandability of code. "Coding Guidelines: Finding the Art in the Science" by Robert Green and Henry Ledgard addresses a number of often overlooked aspects of code design, including:

  • Statement alignment.
  • Component naming.
  • The use of white space.
  • Syntax highlighting.

Many developers feel that work done to improve the appearance and understandabililty of code is wasted effort. They will often work to make code as compact and sometimes as obscure as possible.

This might work well for them while the function of the code is recently developed in their own head. But someone, even themselves, trying to maintain or improve the code sometime in the future would likely find it very difficult to understand.

Using principles such as those above can, over the long run, decrease development costs and improve code performance.

Dealing with Android Fragmentation

So called Android fragmentation is caused by the large number of Android device types and operating system versions deployed in the market.  It's the flip side to the benefit of having a wide variety Android devices and capabilities.

There are currently over a thousand different types of Android devices on the market. It's simply not possible to support all of these without accomodating variations in device design.

Google provides a number of tools for addressing the compatibility necessary to serve this diverse universe of devices. These include:

Unified Support for Tablets and Handsets

Android 4.0 combines the support of tablets and handsets into a single release.

The Holo Theme Family

In Android 4.0 Google has made the inclusion of the unmodified Holo theme family a compatibility requirement for devices running Android 4.0 and forward. This will provide a level of uniformity across device implementations.

Support for Multiple Screens

Provides mechanisms for supporting multiple screen sizes and densities.

Action Bar Backward Compatibility

Google has recently developed a set of classes to give the Action Bar backward compatibility for pre Android 3.0 devices.  These classes invoke the action bar design pattern on pre-API 11 devices and the built-in Action Bar on devices supporting API 11 or greater.

Android Compatibility Package

This library is available through the SDK Updater. It gives backward compatibility for the new Fragments feature.

Compatibility Guidelines

Google provides guidelines on achieving compatibility across devices.

Android Action Bar Backward Compatibility

The Action Bar is a consistently formatted navigation and option selection area at the top of a screen with an overflow area at the bottom.
 
Key aspects of the Action Bar include:
  • It's a replacement for the menu feature.
  • It was introduced in Android 3.0 and refined in Android 4.0.
  • It's included in activities that use the Holo theme family.

Elements of the Action Bar graphic include:

  • Application icon.
  • Application name.
  • Up navigation to a parent screen.
  • Built-in tab navigation for switching between fragments.
  • Drop-down list for alternative navigation such as sort by a different criteria.
  • Important actions for a given app such as search and share.

Google has recently developed a set of classes to give the Action Bar backward compatibility for pre Android 3.0 devices.  These classes invoke the action bar design pattern on pre-API 11 devices and the built-in Action Bar on devices supporting API 11 or greater.

This is part of a larger set of capabilities for supporting application compatibility with multiple device environments including tablets and handsets and various screen sizes.

Using JavaScript, jQuery and HTML5 with Cloud-Based Web Development Tools

Cloud based web development tools (such as Squarespace) are making web development easier. Their WYSIWYG editors even make simple web update accessible to non technical users. Web developers can concentrate on the more complicated, higher value added tasks, while their clients make simpler updates such as text changes and blogging.

By adding JavaScript, jQuery and HTML5 to the mix, sophisticated, cost effective websites can be developed.