Monday, September 26, 2011

Android state management Tutorial

Introduction
When creating android applications, that are not trivial, it is important to keep in mind that android activities, widgets, and services have somewhat autonomous lifecycles that are controlled by the operating system itself. This is profound impacts on how you have to think about applications, since they are no longer something unified, and instead are a lot of different parts that are being orchestrated somewhat randomly. For example, an application’s process can be terminated anytime, or its activities can be terminated, or its services can be restarted. If you do not plan for such diversity in lifecycle states when building each widget service or activity, you will have a really tough time syncing them all up in the final application.


What is the right way
It is best not to think of the application as one monolithic unified chunk of code. It is really difficult to think of the application in terms of the Linux process or its constituent activities, widgets and services. There are so many moving parts and pieces, it is easy to get disoriented in the mix of these things, especially when it comes to keeping track of lifecycle states. A simple example of this is the tendency of standard activities to restart when the screen orientation is changed. If you are not planning for this from the get go, here you have a very nasty surprise the first time the user changes the screen orientation. Especially if you are keeping state information in the scope of the activity object! This can be disabled in the android manifest, but it sets the stage for how you have to think differently about applications.

So what is the right way? It is best to keep state information persisted, along major checkpoints in the code. This means that you have to constantly save pertinent information to some service persistent store, whether to file or the database, it does not matter. As long as information is stored, you can have some hope of reconstituting the last known state of an activity, service, widget. So you have to make sure when these activities services or widgets are reconstituted that you check for any pre-existing stored state information. This will ensure that your applications can restart from failure (unintended or intended).

Service


In your service, make sure to keep track of all pertinent state information and save key information to persistent storage. This should be done when major state changes occur. Activities and widgets will also need to interact with your service. So it is really important to restore state on failure (and sense whether a start is clean or is a restart from failure). This will ensure that even if the service is restarted, any activities and widgets that rely on it will function moving forwards. For example, if your service was running a long-running task, before it got terminated, then on restart, it must ensure that that long-running task can be resumed, or restarted. Either ways any dependent widgets are activities would have to query the service to determine their initial state when they first bind to it. Alternatively, if you do not want to query the initial state, you can have the widgets and activities store their key pertinent state information to persistence as well.

Activity
When activity launches, and it depends on the service, it should start the service and bind to it. If the service was restarted unexpectedly and the activities not aware, it is best to have the activity query the service to figure out the initial state that should be set in the activity itself. Alternatively, the activity can store its own state information and restore it on startup. So if the activity kicks off some long-running process, it is best to store this state information to persistence. This way if the activity is restarted for whatever reason, it can pick up where it left off.

Summary
The key to all of this, is to make sure that key pertinent state information is persisted by an activity or service as it progresses through its lifecycle. You can implement complicated syncing between an activity and the service, to ensure that they are in the correct state at startup, but it might just be easier for each of the parties involved to store this information separately and restore it independently on startup or restart (and detect if start is clean or is a restart from failure). This way, you can create applications that are resilient to process terminations, service restarts, and even device restarts.

Further reading in related categories
Android

Android Location Providers – gps, network, passive - Tutorial
The best way to handle GPS is to use the “network” or “passive” provider first, and then fallback on “gps”, and depending on the task, switch between providers. This covers all cases, and provides a lowest common denominator service (in the worst case) and great service (in the best case).
Android Event Dispatch Thread or Main Thread - Tutorial
Android applications run in a native Linux process, in the underlying Linux OS. This process houses activities (screens), widgets, and services (non visual long running application parts). When working with Android apps, it is important to remember to keep long running code running in threads that are not tied to the main thread or event dispatch thread, in order to get an “application not responding” error. A common mistake that is made is long running tasks are performed in this EDT/main thread, and this leads to lots of application failures.
Android custom themed Dialog - Tutorial
I was trying to create dialogs and alert dialogs that look the same on all Android smartphones, after he realized the different types of smart phones do something different with the default themes and make buttons, dialogs, etc. look very different from one phone to the other. Everything looks very different in the simulator than it does on a Droid X or Droid 2 for example. Things look more similar on a Samsung Galaxy S, or HTC Incredible, but even there you can see some differences.
Android custom skinned Button - Tutorial
Some Android phone manufacturers replace the default themes, and styles, and drawable assets with what they think looks good and customized. Unfortunately, the side effect of this customization is that what works great in the emulator, and most phones simply does not work these devices. Eg, Motorola Droid 2 and X have a customized theme that uses really dark backgrounds, and red foreground colors. This can wreck many applications that are designed for a light background with dark text color.
Using JSON for mobile object exchange - Tutorial
I've been working with various object encoding schemes to get information transferred over the network between services and mobile apps running on Android and BlackBerry. On Android, I figured I would try using Java object serialization, and that works some of the time, and not for anything complex. I wish the object serialization and deserialization mechanism in GWT would be ported over to all these mobile environments, but I digress. This tutorial outlines the use of JSON for this purpose.
Android Application Provisioning Strategies
There aren't any good solutions out right now. App provisioning and management are left out of the M5 SDK, and we have to wait until a future release to see this in place. Once it's in place, these other strategies outlined here may or may not be viable. However, if you can preload an APK file into a device, then the solutions outlined here might work for you.
Android WebView (WebKit) Tutorial
This article shows you the limitations and capabilities of the WebView component. You will see how to download files from the network and use them in HTML, as well as assets loaded in the APK file.
Android Service creation and consumption Tutorial
This tutorial will show you how to create a simple service, that does not use IPC (inter process communication). Services are great for running long running tasks and business logic, outside an Activity, which is tied to the user interface. For example, if you have a background task that has to download data periodically, then you should put that task in a Service. You can explicitly start a service and stop it as well. With IPC you can connect to a running service and call methods on it, however, in this example, I won't be using any IPC; instead all data transfer will happen via a shared object and a listener.
Android Animation Framework Tutorial
This tutorial is an introduction to the built in animation frameworks that are part of the Android UI library. Without writing any animation/drawing code, you can do 2 types of animations - layout transitions that affect ViewGroups, and sequences inside a View. You can also do frame by frame animation, but this tutorial will not cover that. The basics covered here affect layout transitions, and animation of a View itself, using tweening animation, which includes each of the following effects (or any combination) - Alpha, Rotate, Scale, and Translate.
Android ListView and custom adapter Tutorial
This tutorial will show you how to use ListView to display selectable lists of non trivial data, using complex cell renderers. The ListView is a selectable list. You can attach a variety of data models to it and load different display layouts (cell renderers). You can create your own model and cell renderer. This model-view combo is called an Adapter. In this tutorial, I will show you how to extend create your own Adapter from scratch, and create your own cell renderers from scratch as well.
Android LinearLayout Tutorial
This tutorial shows you how to use the LinearLayout container (using Java code, not XML markup), which is the simplest layout mechanism available on Android. If you're familiar with Swing's BoxLayout then you will have a good idea of what this container has to offer. Linear layouts are really simple… you can add components horizontally or vertically to a ‘bag’ or ‘box’.
Android UI Themes Tutorial
This tutorial will show you how to use Android's theme-ing capabilities. You can set background color, image, etc. on widgets, dialogs, and activities.
Android TableLayout Tutorial
This tutorial will show you how to use the TableLayout container, which is like an HTML table. The UI layout code is done in Java, not XML. A class (LayoutUtils) is provided to make it easier to attach layout params to View objects.
Android Option and Context menu Tutorial
This tutorial will show you how to create options menu (hooks into the MENU button) and context menu (press and hold a component).
Android XML View inflation Tutorial
This tutorial will show you how to instantiate or inflate a View from XML; this is useful for components that don't provide a Java API to tweak with certain style attributes. The Button class is used as an example; you can only get certain styles to show up via XML that aren't available via the Java API.
Android Activity and sub-Activity Tutorial
This tutorial will show you how to create a sub-Activity from a calling-Activity, and process the results produced by the sub-Activity, if you want to do so. Also, the various ways of launching a sub-Activity are covered, along with the Android Activity history stack. A subclass of Activity is also provided that makes it trivial to launch sub-Activities and respond to results from them.
Android SDK and tools - Getting started
This tutorial has helpful pointers for developers who are just getting started with Android. In addition to Google’s documentation on the SDK itself, there are lots of tools that come with the SDK and others that you can download elsewhere that make it a little bit easier to work with Android.
Android - How to build a service-enabled Android app - Part 3/3 Multithreading
I've written 3 tutorials to show you how to create a service enabled Android application that performs all of it's network I/O in a background thread (not the UI thread). These tutorials are split into three parts. This tutorial shows you how to use background threads to perform long running network IO operations, so that the main UI thread is not locked up.
Android - How to build a service-enabled Android App - Part 2/3 Networking
I've written 3 tutorials to show you how to create a service enabled Android application that performs all of it's network I/O in a background thread (not the UI thread). These tutorials are split into three parts. This one shows you how to use Apache HTTP Client to connect to services over HTTP or HTTPS and exchange serialized Java objects with services.
Android - How to build a service-enabled Android app - Part 1/3 UI
I've written 3 tutorials to show you how to create a service enabled Android application that performs all of it's network I/O in a background thread (not the UI thread). This tutorial shows you how to build a simple UI without using XML, by writing Java code to layout the UI.
read more..

10 Best Open Source Android Applications

I used to study code from famous open source projects to check out how others execute specific features as well as to learn from them. (I am a firm believer of the fact that you need to read good code to write good code)

Not Long Ago I have been following up a selection of good open source Android apps development and considered itemizing them here in order that it could be useful for many others.
Example Apps by Android Team.

Could there be a better way to start off without going through the code of the developers who developed the framework? These are 15 various android sample apps developed by the primary developers of the Android framework. These include a few games, photostream, time display, home display shortcuts etc.

url : http://code.google.com/p/apps-for-android/

Remote Droid

RemoteDroid is undoubtedly an android app which turns your phone into a wireless keyboard and mouse along with touchpad, using your own wireless network. You can learn lot of things like linking to a network, managing user finger motion etc from its source.

url: http://code.google.com/p/remotedroid/

TorProxy and Shadow

TorProxy is an implementation of Tor for Android mobiles. Along with Shadow, it enables you to surf internet site anonymously through your cell phone. You can study regarding tunnelling socket connections, managing cookies etc by reading it’s source code.

url: http://www.cl.cam.ac.uk/research/dtg/code/svn/android-tor/ and http://www.cl.cam.ac.uk/research/dtg/android/tor/

Android SMSPopup

It is an Android app that will intercepts incoming text messages and shows them in the pop-up window. Besides becoming a time saver, this app also shows us the best way to interface with the built-in application that handles SMS.

url: http://code.google.com/p/android-smspopup/

Standup Timer

Standup Timer is an Android application that behaves as a basic, stand-up meeting stopwatch. It can be used to ensure that your stand-up assembly completes on time, and provides each of the members the same share of time to state their progress. You can learn how to operate the timer features simply by reading through the source code. In addition this applications has clear distinction between view, model etc and has large amount of util procedures that we can reuse in our app.

url: http://github.com/jwood/standup-timer

Foursquare

It is a four square client for android. This app is basically divided into two components; Reading through the source code you can discover how to make

url: http://code.google.com/p/foursquared/

Pedometer

The pedometer app attempts to take the number of steps you take every day. However the count isn’t precise, you can learn different things such as interacting with accelerometer, doing voice updates, running background services etc by just studying its source code.

url: http://code.google.com/p/pedometer/

opensudoku-android

OpenSudoku is an easy open source sudoku game. You can learn the best way to show things in a grid in your view and also how to interact with a website by reading its source code.

url: http://code.google.com/p/opensudoku-android/

ConnectBot

ConnectBot is a Secure Shell client for the Android platform. You will find lot of good stuff about this app’s source code. Check it out for your self

http://code.google.com/p/connectbot/

WordPress for Android

How can a person expect a list of apps from me without mentioning WordPress This android app is from the official WordPress development team. You can learn steps to make XMLRPC calls (as well as other cool things) by reading its source code.

url: http://android.svn.wordpress.org/trunk/

If you got worthwhile open source android apps from where we could learn something, then do leave a comment and I will include them up here, If anyone interested in learning Android app programming can visit EDUmobile.ORG read more..