Android Bound Services Using Inter Process Communications

Android Service components can be implemented using a number of mechanisms.  If you want your Service to be able to communicate with other applications running in separate processes, using Inter Process Communications (IPC) is one approach.

The diagram below shows the major classes and methods needed in the binding activity and bound service.  The details of this implementation can be found on the Android Developers Web site here on the Bound Services page

In summary, the major classes involved are:

  • Service - Application component for longer-running operations that do not interface directly with the user.
  • ServiceConnection - Interface for monitoring a service.
  • Messenger - Creates a Messenger pointing to a Handler in one process, and handing that Messenger to another process.
  • Message - Description and arbitrary data object that can be sent to a Handler.
  • IBinder - Interface for a remotable object.
  • Handler - allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.

Android/PHP/JQuery RESTful JSON MySQL Client-Server Overview

The title of this blog entry is quite a mouthful.  The purpose is to give a broad overview of the moving parts necessary to implement an application with client mobile and desktop devices that interact with a server database to alter and retrieve data.

I won't define all the classes, methods and acronyms on the graphic as they're easy to look up using an Internet search.  There are other choices that can be made for the details of the implementation, but this should provide a starting point for thinking through the necessary elements.

The communication vehicle for client-server interaction is typically the Internet Protocol Suite.

 

Android Broadcast Receivers

Broadcast Receivers are one of the four basic Android components, along with Activities, Services and Content Providers.  Broadcast Receivers respond to Intents issued by the Android system or Android apps.  It's one way to respond to "things happening" on the user device.

The video below from the training course Learning Android App Programming explains the basics of Broadcast Receivers.​

SQL Database Join Operations

It can be challenging to remember the details of all the SQL Join operations.  A convenient way to do this is to use Venn diagrams shown below. For examples of SQL Joins, go here

Commonly used SQL Join operations are:

  • inner join: requires each record in the two joined tables to have matching records.
  • outer join: does not require each record in the two joined tables to have a matching record.

Android Button Listener Code Dissected

Android listeners are the mechanism used to respond to user interaction with a display screen.  Setting up a listener is a very common Android coding task.​  Although it can be done with just a few lines of code, it involves a number of elements that must be configured to interact correctly.

​The diagram below from the video training course Learning Android App Programming dissects the code to establish a listener for a screen button.

Android Service Methods

Android Services can be configured to run in the same thread as the interface activity or a separate background thread.  The diagram below from the video training course Learning Android App Programming details the methods used to start, stop and send messages to a service.​

Android Cursor Interface

An Android Cursor provides read-write access to a data set from an SQL Database.  The Android Cursor interface is a bit of a naming paradigm misdirection.  We normally think of a cursor as an indicator on our computer screen as to where we can type.  And we usually think of the cursor as primarily moving horizontally. he Android Cursor is more complex than this and its cursor movement is primarily vertical, indicating rows in a matrix.  You can think of a Cursor as providing access to an array of data.

The chart below from the video training course Learning Android App Programming provides some convenient visual cues to help understand and remember Android Cursor functionality.

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/

Creating a 3D Effect in 2D HTML5 Canvas Games

HTML5 Canvas doesn’t include a built-in 3D context. Without using an add-on product such as WebGL (www.khronos.org/webgl), 3D has to be simulated using the 2D context.

Some games require the sophistication of a true 3D engine like WebGL. However, many games built using the Canvas 2D context can be significantly enhanced by simulating aspects of 3D motion.

In the Ballpark sample game from HTML5 Canvas for Dummies, the thrown baseball is simulated moving away from the ball thrower toward the ball player along a simulated z axis third dimension. The z axis 3D effect is accomplished by decreasing the size of the baseball in proportion to it's movement upward along the 2D y axis.

You can play the game yourself by clicking here.​  To see the full code, right click on the game web page and select View Page Source.

To simulate 3D movement using this technique, the following steps were used:

1.    Assign a z axis variable to each new object.

Along with the xPos and yPos variables, assign a zPos variable as in code section S2 assignments for baseballs:

     ball[b].zPos = zStart;

2.    As the object moves, update the z position.

In the sample game, in code section R8, the z position is calculated based  on the y axis position (yPos) and a z sizing factor (zSizeFact):

     var newZPos  = (ball[b].yPos/canvasBL.height) * zSizeFact;

     ball[b].zPos = newZPos;  

3.    Fix the z position under specified conditions.

In the sample game, the baseball is simulated to move along the z axis only away from the ball thrower. Also, to simplify the simulation, only movement up the y axis is used to increase z axis movement. So, when the ball starts to move down on the y axis, the z position is fixed. This code is in sections R9-R12:

     // FIX Z position of zFix is greater than zero.      

     if(ball[b].zFix > 0)  {ball[b].zPos = ball[b].zFix};

     // Z FIX check for not already set.

     if(ball[b].zFix == 0)

     {   // Z FIX conditions check. 

        var newYPos  = ball[b].yPos;

        if(((newYPos > curYPos) || (ball[b].bounce)) && (curYPos < zFixMaxY))

        {  // FIX Z POSITION at current level and no smaller than minSize.

           ball[b].zFix = Math.max((curYPos/canvasBL.height)*zSizeFact, minSize);   }   }​

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.