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.

Sunday, May 31, 2009

Observer Pattern in Java

As i was going through the different source code files of the Java Util package, i found the implementation of the Observer Pattern ( see the GoF book for more information on this pattern) in the two classes - namely Observer.java and Observable.java. i would like to throw some lights on these two classes. These two classes can be found in the Java\j2se\src\share\classes\java\util folder of the JDK source code.

But first of all, i need to give you a practical example of why we need observer pattern in the first place.

Suppose, we have a document which can be viewed simultaneously by three different views – say one view represents a line graph chart, another view represents it in a spreadsheet, yet another view represents a pie chart. Now suppose the spreadsheet view makes some modification to the document. If the other two views don't update themselves with this changed state of the document, different views will be in inconsistent states. So we need some mechanism to notify the other two views whenever the spreadsheet view updates the document. This is done through Observer pattern in which whenever the document changes stete, it notifies all of its views. The views in turn updates themselves with the latest data.
The class diagram will look like the following.




And the sequence diagram of this pattern is like this.


What these two diagrams essentially depict is that in the Observer Pattern, we have a Subject, which can attach one or more Observers through its Attach() function. Whenever it changes its state it Notifies all the attached Observers through its Notify function. The observers in turn synchronize their states with that of the Subject through the GetSubjectState function.

Now let me try to dissect the Java observer pattern.

Let us first start with the Observable.java class. As the name suggests it is the class which will implemented functionalities for being observed. Or in other words it is the class which helps in designing the Subject class of the Observer pattern discussion of the GoF book. We need to extend this class to get the Subject class.

Let us try to dissect this class. The following functions are there in this class:

Data Members: It has a vector to hold all the observers that are interested in observing this observable class. It has another boolean data member called "changed" to indicate if anything has changed in the Subject class ( which will be derived from this Observable class).

Constructor : This class has a no argument constructor to construct an empty vector of Observers.

Member Functions :

  • addObserver : To add an observer to its list of Observers.

  • deleteObserver : To delete a particular observer from the list of the observers

  • notifyObservers : there are two overloaded versions of this function. One takes an Object parameter as an argument and the other does not take any argument. The task of this function is to notify all the attached observers when any data of the subject gets changed. To check whether the data is changed it evaluates the boolean "changed" data member. This function also calls the update function of each observer objects to ask them to get in sync with the subject's changed state. The overloaded version that takes an one argument parameter is used to let the observers know about which attribute is changed. And the other version of this function which does not take any argument does not let the observer know about which attribute is changed.
  • deleteObservers : This function removes all the observers attached to this subject.

  • setChanged : This function sets the boolean data member "changed".

  • clearChanged : This function resets the boolean data member "changed".

  • hasChanged : This function helps us to know whether the data of the subject has been changed or not. 

  • countObservers : This function returns the number of observers attached to this subject.
This is all about the Observable class which helps us to define to Subject class.

The Observer.java defines an interface called Observer having just one abstract function called update (Observable o, Object arg). As the name suggests, the Observer class that will implement this interface will override the update function to set the attribute passed as an argument (arg) from the Subject class. This method is called whenever any attribute in the Subject class gets changed.

Now let us try to see an example to understand how this Observer Pattern is used.

Let us first extend the Observable class to create the Subject class.

package com.somitsolutions.training.java.observerpattern;

import java.util.Observable;

public class Subject extends Observable {

private String name;
private float price;

public Subject(String name, float price) {
this.name = name;
this.price = price;
}

public String getName() {
return name;
}
public float getPrice() {
return price;
}
public void setName(String name) {
this.name = name;
setChanged();
notifyObservers(name);
}

public void setPrice(float price) {
this.price = price;
setChanged();
notifyObservers(new Float(price));
}
}

As this is clear from the implementation of the Subject class, that whenever we call the setter function to change the attributes of the Subject's object, we call the notifyObservers and pass that attribute as a parameter.


Now let us see how we create two different observers namely NameObserver and PriceObserver to observe these two attributes of the Subject class.

// An observer of name changes.
package com.somitsolutions.training.java.observerpattern;

import java.util.Observable;
import java.util.Observer;

public class NameObserver implements Observer {

private String name;
public NameObserver() {
name = null;
System.out.println("NameObserver created: Name is " + name);
}
@Override
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
if (arg instanceof String) {
name = (String)arg;
System.out.println("NameObserver: Name changed to " + name);
}
}
}


// An observer of price changes.
package com.somitsolutions.training.java.observerpattern;

import java.util.Observable;
import java.util.Observer;

public class PriceObserver implements Observer {

private float price; public PriceObserver() {
price = 0;
System.out.println("PriceObserver created: Price is " + price);
}
@Override
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
if (arg instanceof Float) {
price = ((Float)arg).floatValue();
System.out.println("PriceObserver: Price changed to " + price);
}
}

}

As it has become clear from the above two implementations that the update function actually helps in synchronizing the state of the concrete observers with that of the Subject.

Now the client of the Observer framework will look like the following :

package com.somitsolutions.training.java.observerpattern;

public class Main {

public static void main(String args[]) {

// Create the Subject and Observers.
Subject s = new Subject("Kheer Kadam", 20.5f);

NameObserver nameObs = new NameObserver();
PriceObserver priceObs = new PriceObserver();

// Add those Observers!
s.addObserver(nameObs);
s.addObserver(priceObs);

//Initial Subject States
System.out.println("Initial states of Subject");
System.out.println("Name : " + s.getName());
System.out.println("Price : " + Float.toString(s.getPrice()));

// Make changes to the Subject.
s.setName("Gulabjamun"); // It prints NameObserver: Name changed to Gulabjamun

s.setPrice(15.0f); //It prints PriceObserver: Price changed to 15.0

s.setPrice(30.5f); //It prints PriceObserver: Price changed to 30.5

s.setName("Rasgulla"); // It prints NameObserver: Name changed to Rasgulla
}
}

Hope the above discussion will help people understand of how the Java supports implementing the Observer pattern.

Thursday, March 12, 2009

Bridge Pattern in C++



When I studied almost all of the Gang of Four Design Patterns in 2005 or 2006, I knew only one language: C++.

Now I am proficient in multiple software languages and my viewpoint about Design Patterns has also matured...

So, here we go.

Here's the source code of the Bridge Pattern, the code is extracted from the presentation.

//Coord.h

#ifndef COORD_H

#define COORD_H


struct Coord {

int x, y;

Coord(int x = 0, int y = 0) : x(x), y(y) {}

};


#endif


// Window.h


#ifndef WINDOW_H

#define WINDOW_H


#include "Coord.h"

#include "WindowImp.h"


class Window {

public:

Window();

virtual ~Window();


void GetWindowImp(int typeOfImplementation); // Attaches implementation

void DrawLine(const Coord& begin, const Coord& end);

void DrawRect(const Coord& topLeft, const Coord& bottomRight);


protected:

WindowImp* imp = nullptr;

};


class IconWindow : public Window {

public:

void DrawBorder(const Coord& topLeft, const Coord& bottomRight);

};


class TransientWindow : public Window {

// Can add specific behavior if needed

};


#endif



// Window.cpp


#include "Window.h"

#include "WindowSystemFactory.h"

#include <iostream>


Window::Window() {}


Window::~Window() {

delete imp;

}


void Window::GetWindowImp(int typeOfImplementation) {

imp = WindowSystemFactory::Instance()->MakeWindowImp(typeOfImplementation);

}


void Window::DrawLine(const Coord& begin, const Coord& end) {

if (imp) imp->DeviceLine(begin, end);

}


void Window::DrawRect(const Coord& topLeft, const Coord& bottomRight) {

if (imp) imp->DeviceRect(topLeft, bottomRight);

}


void IconWindow::DrawBorder(const Coord& topLeft, const Coord& bottomRight) {

DrawRect(topLeft, bottomRight); // Uses bridged implementation

}


// WindowImp.h

#ifndef WINDOWIMP_H

#define WINDOWIMP_H


#include "Coord.h"


class WindowImp {

public:

virtual ~WindowImp() = default;

virtual void DeviceLine(const Coord& begin, const Coord& end) = 0;

virtual void DeviceRect(const Coord& topLeft, const Coord& bottomRight) = 0;

};


class XWindowImp : public WindowImp {

public:

void DeviceLine(const Coord& begin, const Coord& end) override;

void DeviceRect(const Coord& topLeft, const Coord& bottomRight) override;

};


class PMWindowImp : public WindowImp {

public:

void DeviceLine(const Coord& begin, const Coord& end) override;

void DeviceRect(const Coord& topLeft, const Coord& bottomRight) override;

};


#endif


// WindowImp.cpp


#include "WindowImp.h"

#include <iostream>


void XWindowImp::DeviceLine(const Coord&, const Coord&) {

std::cout << "XWindow: Drawing Line\n";

}


void XWindowImp::DeviceRect(const Coord&, const Coord&) {

std::cout << "XWindow: Drawing Rectangle\n";

}


void PMWindowImp::DeviceLine(const Coord&, const Coord&) {

std::cout << "PMWindow: Drawing Line\n";

}


void PMWindowImp::DeviceRect(const Coord&, const Coord&) {

std::cout << "PMWindow: Drawing Rectangle\n";

}



// WindowSystemFactory.h

#ifndef WINDOWSYSTEMFACTORY_H

#define WINDOWSYSTEMFACTORY_H


class WindowImp;


enum WindowImplementation {

XWindowImplementation,

PMWindowImplementation

};


class WindowSystemFactory {

public:

static WindowSystemFactory* Instance();

WindowImp* MakeWindowImp(int type);


private:

WindowSystemFactory() = default;

static WindowSystemFactory* instance;

};


#endif


// WindowSystemFactory.cpp

#include "WindowSystemFactory.h"

#include "WindowImp.h"


WindowSystemFactory* WindowSystemFactory::instance = nullptr;


WindowSystemFactory* WindowSystemFactory::Instance() {

if (!instance) {

instance = new WindowSystemFactory();

}

return instance;

}


WindowImp* WindowSystemFactory::MakeWindowImp(int type) {

if (type == XWindowImplementation) return new XWindowImp();

if (type == PMWindowImplementation) return new PMWindowImp();

return nullptr;

}



//============================================================================

// Name : BridgePattern.cpp

// Author : Som

// Version :

// Copyright : som-itsolutions

// Description : Hello World in C++, Ansi-style

//============================================================================


#include "Window.h"

#include "Coord.h"

#include "WindowSystemFactory.h"

#include <iostream>


int main() {

const Coord pt0(1, 2);

const Coord pt1(7, 8);


// X-based Icon Window

IconWindow* xIcon = new IconWindow();

xIcon->GetWindowImp(XWindowImplementation);

xIcon->DrawBorder(pt0, pt1);


// PM-based Transient Window

TransientWindow* pmTransient = new TransientWindow();

pmTransient->GetWindowImp(PMWindowImplementation);

pmTransient->DrawRect(pt0, pt1);


// PM-based Icon Window

IconWindow* pmIcon = new IconWindow();

pmIcon->GetWindowImp(PMWindowImplementation);

pmIcon->DrawLine(pt0, pt1);


delete xIcon;

delete pmTransient;

delete pmIcon;


return 0;

}