Saturday, October 10, 2009

WiFi Subsystem in Android

As i was trying to understand the WiFi subsystem of Android i came out with a diagram to depict the flow of events between different functional blocks of it. I would like to share it with you.

It goes like this:



Hope it will help the Android developers' community.

Thursday, October 8, 2009

Tabs in Android - through an example

As i was trying to experiment with the different widgets of Android, i developed this example to show how Tab works in Android.

And the application looks like the following:



And the next tab looks like:



The first thing we need to to do is working on the XML layout.

The XML code of the layout my example is as follows:

(?xml version="1.0" encoding="utf-8"?)
(LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
)

(TabHost android:id="@+id/TabHost01" android:layout_width="wrap_content" android:layout_height="wrap_content")
(TabWidget android:id="@android:id/tabs" android:layout_width="wrap_content" android:layout_height="wrap_content" /)
(FrameLayout android:id="@android:id/tabcontent" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingTop="65px")
(AnalogClock android:id="@+id/AnalogClock01" android:layout_width="wrap_content" android:layout_height="wrap_content")(/AnalogClock)
(DigitalClock android:text="DigitalClock01" android:id="@+id/DigitalClock01" android:layout_width="wrap_content" android:layout_height="wrap_content")(/DigitalClock)
(/FrameLayout)
(/TabHost)
(/LinearLayout)

And the Java code for this example is as follws:

import android.app.Activity;
import android.os.Bundle;
import android.widget.TabHost;

public class tabexample extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

TabHost tabs = (TabHost)findViewById(R.id.TabHost01);

tabs.setup();

TabHost.TabSpec spec1 = tabs.newTabSpec("tag1");

spec1.setContent(R.id.AnalogClock01);
spec1.setIndicator("Analog Clock");

tabs.addTab(spec1);

TabHost.TabSpec spec2 = tabs.newTabSpec("tag2");
spec2.setContent(R.id.DigitalClock01);
spec2.setIndicator("Digital Clock");

tabs.addTab(spec2);
}
}

Hope this helps the newcomers of Android...

Saturday, August 15, 2009

Inter Process Communication in Android through Intent

In Android, one of the nice ways for passing data between different processes is through the help of Intent. In the following example i have tried to explain it by two different applications. One application is called the IntentSupplier. This is started from another application called IntentExample. The application IntentSupplier passes some string data to the IntentExample app through the help of an Intent object which the IntentSupplier application displays in a message box.

The IntentSupplier application looks like the following.




When we click one of the buttons it passes its string data to the IntentExample which looks like the following.



The source code for IntentSupplier is as follows:

package android.training.intentsupplier;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class IntentSupplier extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button button1 = (Button)findViewById(R.id.Button01);

Button button2 = (Button)findViewById(R.id.Button02);

button1.setOnClickListener(onClickButton1);
button2.setOnClickListener(onClickButton2);

}

private OnClickListener onClickButton1 = new OnClickListener() {

public void onClick(View v){

if (v.getId() == R.id.Button01){

returnResult("Message1 coming from IntentSupplier");
}
}
};

private OnClickListener onClickButton2 = new OnClickListener() {

public void onClick(View v){

if (v.getId() == R.id.Button02){

returnResult("Message2 coming from IntentSupplier");
}
}
};

void returnResult(String msg) {

Intent i = new Intent();

i.putExtra("android.training.intentsupplier.resultfromintentsupplier", msg);

setResult(RESULT_OK, i);

finish();
}

}


Look at the function

void returnResult(String msg).

Here at the line i.putExtra("android.training.intentsupplier.resultfromintentsupplier", msg), we are basically parceling the data (msg) and giving it a label called resultfromintentsupplier. Please see how the package info is prefixed with this label.

The source code for the IntentExample is as follows:

package android.training.intentexample;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class IntentExample extends Activity {

static final int REQUEST_CODE = 1001;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);

Intent getMessageFromIntentSupplier = new Intent();

getMessageFromIntentSupplier.setClassName("android.training.intentsupplier", "android.training.intentsupplier.IntentSupplier");

getMessageFromIntentSupplier.setAction("android.training.intentsupplier.android.intent.action.INTENTSUPPLIERTEST");

getMessageFromIntentSupplier.addCategory("CATEGORY_DEFAULT");

getMessageFromIntentSupplier.setType("vnd.example.greeting/vnd.example.greeting-text");

try {
startActivityForResult(getMessageFromIntentSupplier,REQUEST_CODE);

}

catch(ActivityNotFoundException e) {
Log.e("IntentExample", "Activity could not be started...");
}

}
}

public void onActivityResult(int requestcode, int resultcode, Intent result ) {

if(requestcode == REQUEST_CODE){
if(resultcode == RESULT_OK){
message = result.getStringExtra("android.training.intentsupplier.resultfromintentsupplier");

new AlertDialog.Builder(this)
.setTitle("Msg from Intent Supplier")
.setMessage(message)
.setNeutralButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
// do nothing – it will close on its own
}
})
.show();
}
}
}

}

The AndroidManifest.xml file of the IntentSupplier application looks like the following:

(** Please replace the "(" & ")" brackets with the angular brackets to xmlize the file contents)

(?xml version="1.0" encoding="utf-8"?)
(manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.training.intentsupplier"
android:versionCode="1"
android:versionName="1.0")
(application android:icon="@drawable/icon" android:label="@string/app_name")
(activity android:name=".IntentSupplier"
android:label="@string/app_name")

(intent-filter)
(action android:name="android.intent.action.MAIN" /)
(category android:name="android.intent.category.LAUNCHER" /)
(/intent-filter)

(intent-filter)
(action android:name="android.intent.action.INTENTSUPPLIERTEST" /)
(category android:name="android.intent.category.DEFAULT" /)
(data android:mimeType="vnd.example.greeting/vnd.example.greeting-text" /)
(/intent-filter)
(/activity)
(/application)
(uses-sdk android:minSdkVersion="3" /)
(/manifest)

The main.xml file of the IntentSupplier application looks like the following:

(?xml version="1.0" encoding="utf-8"?)
(LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
)
(TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/)
(Button android:text="Message1" android:id="@+id/Button01" android:layout_width="fill_parent" android:layout_height="wrap_content")(/Button)
(Button android:text="Message2" android:id="@+id/Button02" android:layout_width="fill_parent" android:layout_height="wrap_content")(/Button)
(/LinearLayout)

In this example we have started the IntentSupplier app through the function startActivityForResult. It then waits for the result from the child activity, and once the result arrives, the callback function onActivityResult is called. in this function we extract the data sent from the child activity (by using the function getStringExtra) and show it in a message box.

To run this application we need to run once the IntentSupplier application first.

Hope this discussion becomes helpful for the newbies of Android.

Sunday, July 5, 2009

My first time experience with Android Webkit

As I was trying to play around with WebKit, I tried to load an web page through it in Android. A good starting point for WebKit may be found at

http://developer.apple.com/documentation/Cocoa/Conceptual/DisplayWebContent/DisplayWebContent.html .

The source code of my android application is pretty straight forward.

It goes like this:

public class WebKitExample extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

WebView webView;

setContentView(R.layout.main);

webView = (WebView)findViewById(R.id.appView);

webView.getSettings().setJavaScriptEnabled(true);

webView.loadUrl("http://www.google.com");
}
}

We need to add the XML resource in the main.layout as the following:

(WebView android:id="@+id/appView"
android:layout_height="wrap_content"
android:layout_width="fill_parent" /)

We also need to add the permission to the manifest file as the following:

(uses-permission android:name = "android.permission.INTERNET" /)

And the application will look like the following in the emulator.



Although the example shown here is pretty simple but it can be a starting point in learning Webkit in Android. Hope this helps the newbies of Android.

Sunday, June 14, 2009

Parameterized factory design pattern in Android Media Service Framework

As i was going through the Media framework of Android, i have found the implementation of a parameterized factory pattern in the way MediaPlayerService class creates the concrete media players.

Let me give an idea of the parameterized factory implementation as discussed in the GoF book. It goes like this.

class Creator {

public:

virtual Product* CreateProduct( ProductId id);

};

And the implementation will look like the following:

Product* Creator :: CreateProduct (ProductId id)
{

if (id == Product1) return new Product1;

if (id == Product2) return new Product2;

//repeat for the other products

return 0;

}

Product1, Product2 etc are all derived from the base class Product.

Now let us dissect the Media Framework of Android to see how this design pattern has been implemented to create the different Media players.

The base class of all the players are MediaPlayerInterface which is again derived from MediaPlayerBase.

MediaPlayerService has got a static function called

"static sp createPlayer(player_type playerType, void* cookie, notify_callback_f notifyFunc)"

which actually takes care of the creation of the concrete players namely PVPlayer, MidiFile and VorbisPlayer.

Hence the class MediaPlayerService works as the Factory class for creating the Concrete Players besides handling other responsibilities.

The class MediaPlayerService can be found at \base\media\libmediaplayerservice of the Android source code.

The createPlayer function goes like the following :

static sp(MediaPlayerBase) createPlayer(player_type playerType, void* cookie,
notify_callback_f notifyFunc)
{
sp(MediaPlayerBase) p;
switch (playerType) {
#ifndef NO_OPENCORE
case PV_PLAYER:
LOGV(" create PVPlayer");
p = new PVPlayer();
break;
#endif
case SONIVOX_PLAYER:
LOGV(" create MidiFile");
p = new MidiFile();
break;

case VORBIS_PLAYER:
LOGV(" create VorbisPlayer");
p = new VorbisPlayer();
break;
}
if (p != NULL) {
if (p->initCheck() == NO_ERROR) {
p->setNotifyCallback(cookie, notifyFunc);
} else {
p.clear();
}
}
if (p == NULL) {
LOGE("Failed to create player object");
}
return p;
}

As we can see from the above code that MediaPlayerBase here works as the base class Product. And we create different products (different concrete media players) through the function createPlayer which works as the CreateProduct function in the example at the beginning.

The above similarity shows how a Parameterized Factory Pattern has been implemented in the Android Media Framework by MediaService layer to create different Media Players.

Wednesday, June 3, 2009

Composite Design Pattern in Android View and Widget

The Intent of this design pattern is stated in the GoF book as "Compose Objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly".

To explain it in a simpler fashion, let me give the same example as given in the GoF book. Suppose there is an object called Picture, a graphics object. This picture may consist of other pictures recursively as well as primitive objects like line, rectangle objects etc. All of these part objects which make the whole picture conform to the same Graphic interface. Hence to the client, a part object appears same as the whole picture consisted of other part objects. To draw a whole object, the client simply traverses through the whole picture and draws different parts.

The class diagram of the composite design pattern will look like the following:




The following participants take part in this design pattern:

Component -

it declares the interface for the objects ( part as well as whole)
helps in managing the objects (adding, removing)

Leaf -

represents leaf objects which don't have any children
these are the primitive objects

Composite -

defines behavior for components having children
stores the children

Client -

takes help of the Component interface to manipulate different objects

If you want to know more about the Composite Design Pattern, please have a look at

http://som-itsolutions.blogspot.in/2008/12/composite-design-pattern-is-structural.html

Its all about the theoretical side of the Composite Design Pattern. Now let us try to dissect the Android View and the Widget folders (which are available at \\base\core\java\android) to see how this design pattern has been implemented there.

In Android, the View class works as the Component class. However, the child management part (add component, remove component) has been moved to the Composite class which is the ViewGroup class. Actually the Add and Remove of a component has been declared in an interface called ViewManager and the ViewGroup implements that interface. Also the interface for a Composite object is declared as ViewParent interface and the ViewGroup (the Composite object) implements that as well.

The leaf classes like Button, ImageView etc are deduced either by directly subclassing the View (Component) or from the subclasses of the View (for example, the Button class is derived from TextView class which in turn is directly derived fron the View class). The Composite Class (ViewGroup) is deduced by directly subclassing the View and by implementing the two interfaces namely ViewParent (which defines the interface of a composite object) and ViewManager (which defines the interface from adding and removing components).

As expected the getParent function which is needed to get the Parent of a component is put in the View class (the Component).

The Composite object (ViewGroup) has an array to hold its children.

The simplified version of the class diagram of the Android View and Widgets are as follows:



For simplicity i have not shown the two interfaces namely ViewManager and ViewParent.

Now let us consider the class diagram as presented in the beginning of this discussion. There is a function called Operation. In Android implementation, the onDraw function in the Component (View) plays this role. The DispatchDraw function (which is called when the children are to be drawn) in the composite (ViewGroup) object actually traverses through the list of the objects and calls draw on each of the child object.
This becomes clear when we see the android source code of the dispatchDraw function in the andrroid.view.ViewGroup class. The code is as follows:

 @Override
 protected void More dispatchDraw(Canvas canvas) {

......................
.....................
....................

 for (int i = 0; i < count; i++) {
                final View child = children[i];
                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || 
                                              child.getAnimation() != null)
               {
                   more |= drawChild(canvas, child, drawingTime);
               }
         }
......................
......................

For simplicity, in the class diagram it is shown that the dispatchDraw function is directly calling the onDraw function. However it actually takes help of another function called drawChild which is called on each child object of the ViewGroup object.

This way we can say that Android View and Widgets are some sort of implementation of the Composite Design Pattern.