Drawable Resources

February 21st, 2012 Comments off

A drawable resource is a general concept for a graphic that can be drawn to the screen and which you can retrieve with APIs such as getDrawable(int) or apply to another XML resource with attributes such as android:drawable and android:icon. There are several different types of drawables. We will be explaining some of them, those we always use in business. :-)

1. XML Bitmap

An XML bitmap is a resource defined in XML that points to a bitmap file. The XML can specify additional properties for the bitmap such as dithering and tiling.

Note: You can use a <bitmap> element as a child of an <item> element

XML file must be saved in res/drawable floder. The filename is used as the resource ID.

Elements:

<Bitmap>

Defines the bitmap source and its properties.

Attributes:
xmlns:android
String. Defines the XML namespace, which must be “http://schemas.android.com/apk/res/android“. This is required only if the is the root element—it is not needed when the is nested inside an <item>.

android:src
Drawable resource. Required. Reference to a drawable resource.

android:antialias
Boolean. Enables or disables antialiasing.

android:dither
Boolean. Enables or disables dithering of the bitmap if the bitmap does not have the same pixel configuration as the screen

android:filter
Boolean. Enables or disables bitmap filtering. Filtering is used when the bitmap is shrunk or stretched to smooth its apperance.

android:gravity
Keyword. Defines the gravity for the bitmap. The gravity indicates where to position the drawable in its container if the bitmap is smaller than the container.

Example

XML file saved at res/drawable/bitmap.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <bitmap xmlns:android="http://schemas.android.com/apk/res/android"
        android:src="@drawable/icon"
        android:tileMode="repeat" />


This layout XML applies the drawable to a View:

<ImageView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:src="@drawable/bitmap" />


2. State List

A StateListDrawable is a drawable object defined in XML that uses a several different images to represent the same graphic, depending on the state of the object. For example, a Button can exist in one of several different states (pressed, focused, or neither) and, using a state list drawable, you can provide a different background image for each state.

You can describe the state list in an XML file. Each graphic is represented by an <item> element inside a single <selector> element. Each <item> uses various attributes to describe the state in which it should be used as the graphic for the drawable.

XML file must be saved in res/drawable floder. The filename is used as the resource ID.

Elements:

<selector>

Required. This must be the root element. Contains one or more <item> elements.

Attributes:
xmlns:android
String. Required. Defines the XML namespace, which must be “http://schemas.android.com/apk/res/android“.

android:dither
Boolean. “true” to enable dithering of the bitmap if the bitmap does not have the same pixel configuration as the screen ; “false” to disable dithering. Default is true.

<item>

Defines a drawable to use during certain states, as described by its attributes. Must be a child of a <selector> element.

Attributes:
android:drawable
Drawable resource. Required. Reference to a drawable resource.

android:state_pressed
Boolean. “true” if this item should be used when the object is pressed (such as when a button is touched/clicked); “false” if this item should be used in the default, non-pressed state.

android:state_focused
Boolean. “true” if this item should be used when the object has input focus (such as when the user selects a text input); “false” if this item should be used in the default, non-focused state.

android:state_enabled
Boolean. “true” if this item should be used when the object is enabled (capable of receiving touch/click events); “false” if it should be used when the object is disabled.

Example

XML file saved at res/drawable/state_list.xml:

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_focused="true"
    	android:state_pressed="false"
    	android:state_enabled="true"
        android:drawable="@drawable/back_selected" />

    <item android:state_pressed="true"
   		android:state_enabled="true"
    	android:drawable="@drawable/back_selected" />

    <item android:state_enabled="true"
    	android:state_focused="false"
    	android:state_pressed="false"
        android:drawable="@drawable/back" />

    <item android:drawable="@drawable/back" />
</selector>



This layout XML applies the state list drawable to a Button.

<Button
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:background="@drawable/state_list" />


Run the application and output would be:
1) When the Button is pressed or focused, following will image will appear


2) For normal state


3. Layer List

A LayerDrawable is a drawable object that manages an array of other drawables. Each drawable in the list is drawn in the order of the list—the last drawable in the list is drawn on top.

Each drawable is represented by an <item> element inside a single <layer-list> element.

XML file must be saved in res/drawable floder. The filename is used as the resource ID.

Elements:

<layer-list>

Required. This must be the root element. Contains one or more <item> elements.

Attributes:
xmlns:android
String. Required. Defines the XML namespace, which must be “http://schemas.android.com/apk/res/android“.

<item>

Defines a drawable to place in the layer drawable, in a position defined by its attributes. Must be a child of a <selector> element. Accepts child <bitmap> elements.

Attributes:
android:drawable
Drawable resource. Required. Reference to a drawable resource.

android:id
Resource ID. A unique resource ID for this drawable. To create a new resource ID for this item, use the form: “@+id/name“. The plus symbol indicates that this should be created as a new ID.

android:top
Integer. The top offset in pixels

android:right
Integer. The right offset in pixels.

android:bottom
Integer. The bottom offset in pixels.

android:left
Integer. The left offset in pixels.

All drawable items are scaled to fit the size of the containing View, by default. Thus, placing your images in a layer list at different positions might increase the size of the View and some images scale as appropriate. To avoid scaling items in the list, use a <bitmap> element inside the <item> element to specify the drawable and define the gravity to something that does not scale, such as “center“. For example, the following <item> defines an item that scales to fit its container View:

<item android:drawable="@drawable/image" />



To avoid scaling, the following example uses a <bitmap> element with centered gravity:

<item>
  <bitmap android:src="@drawable/image"
          android:gravity="center" />
</item>


Example

XML file saved at res/drawable/layers.xml:

<?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
      <bitmap android:src="@drawable/bottom_image"
        android:gravity="center" />
    </item>
    <item android:top="20dp" android:left="20dp">
      <bitmap android:src="@drawable/top_image"
        android:gravity="center" />
    </item>

</layer-list>


This layout XML applies the drawable to a View:

<ImageView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:background="@drawable/layers" />


Run the application & output screen would be

4. Level List

A Drawable that manages a number of alternate Drawables, each assigned a maximum numerical value. Setting the level value of the drawable with setLevel() loads the drawable resource in the level list that has a android:maxLevel value greater than or equal to the value passed to the method.

XML file must be saved in res/drawable floder. The filename is used as the resource ID.

Elements:

<level-list>

This must be the root element. Contains one or more <item> elements.

Attributes:
xmlns:android
String. Required. Defines the XML namespace, which must be “http://schemas.android.com/apk/res/android“.

<item>

Defines a drawable to use at a certain level.

Attributes:
android:drawable
Drawable resource. Required. Reference to a drawable resource.

android:maxLevel
Integer. The maximum level allowed for this item.

android:minLevel
Integer
. The minimum level allowed for this item.

Example

XML file saved at res/drawable/layers.xml:

<?xml version="1.0" encoding="utf-8"?>
<level-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:drawable="@drawable/back"
        android:maxLevel="0" />
    <item
        android:drawable="@drawable/back_selected"
        android:maxLevel="1" />
</level-list>



This layout XML applies the drawable to a View

<ImageView android:id="@+id/iv"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:src="@drawable/level_list" />


java code will look like:

package com.mobisys.android.drawable_resources;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class DrawableActivity extends Activity {
    /** Called when the activity is first created. */

	ImageView iv;
	int level;
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.main);
	        iv=(ImageView)findViewById(R.id.iv);
	        level=0;
	        iv.setOnClickListener(new View.OnClickListener(){

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					if(level==0){
						iv.setImageLevel(1);
						level=1;
					}
					else{
						iv.setImageLevel(0);
						level=0;
					}

				}

	        });

	        }
    }


Run the application & click on image




Again click on image:


5. Shape Drawable

This is a generic shape defined in XML.

XML file must be saved in res/drawable floder. The filename is used as the resource ID.

Elements:

<shape>

The shape drawable. This must be the root element.

Attributes:
xmlns:android
String. Required. Defines the XML namespace, which must be “http://schemas.android.com/apk/res/android“.

android:shape
Keyword.Defines the type of shape. Valid values are: Rectangle, line, Oval , ring.

The following attributes are used only when android:shape=”ring”

android:innerRadius
Dimension.The radius for the inner part of the ring (the hole in the middle), as a dimension value

android:thickness
Dimension.The thickness of the ring, as a dimension value

android:useLevel
Boolean. “true” if this is used as a LevelListDrawable. This should normally be “false” or your shape may not appear.

<corners>

Creates rounded corners for the shape. Applies only when the shape is a rectangle.

Attributes:
android:radius
Dimension.The radius for all corners, as a dimension value . This is overridden for each corner by the following attributes.

android:topLeftradius
Dimension.The radius for the top-left corner, as a dimension value

android:topRightradius
Dimension.The radius for the top-right corner, as a dimension value

android:bottomLeftradius
Dimension.The radius for the bottom-left corner, as a dimension value

android:bottomRightradius
Dimension.The radius for the bottom-right corner, as a dimension value

<gradient>

Specifies a gradient color for the shape.

Attributes:
android:angle
Integer.The angle for the gradient, in degrees. 0 is left to right, 90 is bottom to top. It must be a multiple of 45. Default is 0.

android:centerColor
Color.Optional color that comes between the start and end colors, as a hexadecimal value.

android:endColor
Color.The ending color, as a hexadecimal value

android:startColor
Color.The starting color, as a hexadecimal value

android:type
Keyword.The type of gradient pattern to apply. Valid values are: linear, radial, sweep

android:useLevel
Boolean.”true” if this is used as a LevelListDrawable.

<padding>

Padding to apply to the containing View element (this pads the position of the View content, not the shape).

Attributes:
android:left
Dimension.Left padding, as a dimension value.

android:top
Dimension.Top padding, as a dimension value

android:right
Dimension.Right padding, as a dimension value

android:bottom
Dimension.Bottom padding, as a dimension value

<size>

The size of the shape.

Attributes:
android:height
Dimension.The height of the shape, as a dimension value

android:width
Dimension.The width of the shape, as a dimension value

<solid>

A solid color to fill the shape.

Attributes:
android:color
Color.The color to apply to the shape, as a hexadecimal value

<stroke>

A stroke line for the shape.

Attributes:
android:width
Dimension.The thickness of the line, as a dimension value

android:color
Color.The color of the line, as a hexadecimal value

Example 1-Rectangle

XML file saved at res/drawable/gradient_box.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">

  	<gradient
        android:startColor="#FFFF0000"
        android:endColor="#80FF00FF"
        android:angle="45"/>

	<padding android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp" />

    <corners android:radius="2dp" />

</shape>


This layout XML applies the shape drawable to a View:

<TextView android:id="@+id/tv"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
  	 android:text="Rectangle Shape"
    android:background="@drawable/gradient_box"/>


This application code gets the shape drawable and applies it to a View:

   TextView tv1=(TextView)findViewById(R.id.tv);
	        tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.gradient_box));


Output will look like:

Example 2-Oval

XML file saved at res/drawable/gradient_box.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="oval">

  	<gradient
        android:startColor="#FFFF0000"
        android:endColor="#80FF00FF"
        android:angle="0"/>

	<padding android:left="20dp"
        android:top="20dp"
        android:right="20dp"
        android:bottom="20dp" />

        </shape>


This layout XML applies the shape drawable to a View

<TextView android:id="@+id/tv"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
  	 android:text="Oval Shape"
    android:background="@drawable/gradient_box"/>


This application code gets the shape drawable and applies it to a View

TextView tv1=(TextView)findViewById(R.id.tv);
	        tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.gradient_box));



Output will look like this:


Example 3-Line

XML file saved at res/drawable/gradient_box.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="line">

    <stroke android:width="1dp"
    		android:color="#FFFF0000"/>
    <size android:height="5dp" />
</shape>



This layout XML applies the shape drawable to a View:

<TextView android:id="@+id/tv"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:background="@drawable/gradient_box"/>



This application code gets the shape drawable and applies it to a View:

TextView tv1=(TextView)findViewById(R.id.tv);
	       tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.gradient_box));


output will look like this:




Example 4-Ring

XML file saved at res/drawable/gradient_box.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="ring"
  android:innerRadiusRatio="4"
  android:thicknessRatio="10"
  android:useLevel="false">

 <size android:width="100dp"
 	android:height="100dp" />

 <gradient
     android:startColor="#FFFF0000"
     android:endColor="#80FF00FF"
     android:angle="0"/>



This layout XML applies the shape drawable to a View:

<TextView android:id="@+id/tv"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:background="@drawable/gradient_box"/>



This application code gets the shape drawable and applies it to a View:

TextView tv1=(TextView)findViewById(R.id.tv);
	       tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.gradient_box));


Output will look like this:

Android: Using Camera API

February 16th, 2012 No comments

In this tutorial, we will implement one simple camera app with following features:
1) Launch the camera app and it will start the camera with capture and exit button at bottom.
1) On capture, it will capture the picture and show it in ImageView.
2) If you press save, it will save the picture on SD card
3) If you recapture, it will again start the camera to take the picture.
4) If you exit the app, it will exit from the app.

Screenshot

Lets start by creating the project with name CameraApp with CameraAppActivity.

Define Layout XML file

Once the project with Activity, CameraAppActivity is created, first step is to create XML layout file. It is defined as follows:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <LinearLayout android:id="@+id/button_layout"
  	android:layout_alignParentBottom="true"
  	android:orientation="horizontal"
  	android:gravity="center"
  	android:layout_width="fill_parent"
  	android:layout_height="wrap_content">
  	<Button android:id="@+id/exit_button"
  		android:layout_width="wrap_content"
  		android:layout_height="wrap_content"
  		android:layout_gravity="left"
  		android:text="Exit"/>
  	<Button android:id="@+id/ok_button"
  		android:layout_width="wrap_content"
  		android:layout_height="wrap_content"
  		android:layout_gravity="left"
  		android:text="Upload"/>
  	<Button android:id="@+id/recapture_button"
  		android:layout_width="wrap_content"
  		android:layout_height="wrap_content"
  		android:layout_gravity="right"
  		android:text="Recapture"/>
  	<Button android:id="@+id/capture_button"
  		android:layout_width="wrap_content"
  		android:layout_height="wrap_content"
  		android:layout_gravity="right"
  		android:text="Capture"/>
  </LinearLayout>
  <FrameLayout android:id="@+id/preview"
  		android:layout_width="fill_parent"
  		android:layout_height="fill_parent"
  		android:layout_above="@id/button_layout">
  </FrameLayout>
  <ImageView android:id="@+id/img"
  		android:layout_width="wrap_content"
  		android:layout_height="wrap_content"
  		android:layout_above="@id/button_layout"/>
</RelativeLayout>

It has linear horizontal layout of all buttons. All buttons are self-explanatory. FrameLayout to hold the preview of camera. It also have ImageView which will display the preview of the captured picture.

Basic logic is:
1) When application is launched, it will start also the camera preview and will make the ImageView invisible.
2) Camera Preview will be displayed on SurfaceView. So we will create our own SurfaceView preview.
2) When picture is captured, it is displayed in ImageView. So, ImageView is made visible while preview invisible.
3) When OK button is pressed, captured bitmap is saved to SD card.

Create Preview

We will create the SurfaceView on which it will show preview from the camera.

import java.io.IOException;
import java.util.List;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class Preview extends SurfaceView implements SurfaceHolder.Callback{

	SurfaceHolder mHolder;
	public Camera camera;

	public Preview(Context context) {
		super(context);
		// Install a SurfaceHolder.Callback so we get notified when the
		// underlying surface is created and destroyed.
		mHolder = getHolder();
		mHolder.addCallback(this);
		mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		camera.startPreview();
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// The Surface has been created, acquire the camera and tell it where
		// to draw.
		camera = Camera.open();
		try {
			camera.setPreviewDisplay(holder);
			Camera.Parameters parameters=camera.getParameters();
			List<Size> sizes=parameters.getSupportedPictureSizes();
			parameters.setPictureSize(sizes.get(0).width, sizes.get(0).height);
			camera.setParameters(parameters);
			camera.startPreview();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// Surface will be destroyed when we return, so stop the preview.
		// Because the CameraDevice object is not a shared resource, it's very
		// important to release it when the activity is paused.
		camera.stopPreview();
		camera.release();
		camera = null;
	}

}

Activity class

Application only have one Activity, CameraAppActivity. It is as below:

public class CameraAppActivity extends Activity{
	private Bitmap bmp=null;
	ProgressDialog pg=null;
	private Preview preview;
	Button ok_button,click_button,cancel_button,try_again_button;
	//public static byte[] bitmapArray=null;
	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.camera_layout);

		preview=new Preview(this);
		((FrameLayout) findViewById(R.id.preview)).addView(preview);
		findViewById(R.id.preview).setVisibility(View.VISIBLE);
		findViewById(R.id.img).setVisibility(View.GONE);

		ButtonListener listener=new ButtonListener();
		click_button=((Button) findViewById(R.id.capture_button));
		click_button.setVisibility(View.VISIBLE);
		click_button.setOnClickListener(listener);

		try_again_button=((Button) findViewById(R.id.recapture_button));
		try_again_button.setVisibility(View.GONE);
		try_again_button.setOnClickListener(listener);

		cancel_button=((Button) findViewById(R.id.cancel_button));
		cancel_button.setVisibility(View.VISIBLE);
		cancel_button.setOnClickListener(listener);

		ok_button=((Button) findViewById(R.id.ok_button));
		ok_button.setVisibility(View.GONE);
		ok_button.setOnClickListener(listener);
	}

	private class ButtonListener implements View.OnClickListener{

		@Override
		public void onClick(View v) {
			if(v.equals(findViewById(R.id.capture_button))){
				pg=ProgressDialog.show(CameraAppActivity.this, null, "Capturing Image..");
				pg.show();
				preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
			}else if(v.equals(findViewById(R.id.cancel_button))){
				finish();
			}else if(v.equals(findViewById(R.id.ok_button))){
				saveImage();
			}else if(v.equals(findViewById(R.id.recapture_button))){
				findViewById(R.id.img).setVisibility(View.GONE);
				findViewById(R.id.preview).setVisibility(View.VISIBLE);
				preview.camera.startPreview();
				ok_button.setVisibility(View.GONE);
				cancel_button.setVisibility(View.VISIBLE);
				try_again_button.setVisibility(View.GONE);
				click_button.setVisibility(View.VISIBLE);
			}
		}

	}

	ShutterCallback shutterCallback = new ShutterCallback() {
		public void onShutter() {
			//Log.d(TAG, "onShutter'd");
			System.out.println("In ShutterCallback");
		}
	};

	/** Handles data for raw picture */
	PictureCallback rawCallback = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera camera) {
			if(data!=null){
				bmp=BitmapFactory.decodeByteArray(data,0,data.length);
				findViewById(R.id.img).setVisibility(View.VISIBLE);
				((ImageView)findViewById(R.id.img)).setImageBitmap(bmp);
				findViewById(R.id.preview).setVisibility(View.GONE);

				if(pg!=null)
					pg.dismiss();
				ok_button.setVisibility(View.VISIBLE);
				click_button.setVisibility(View.GONE);
				try_again_button.setVisibility(View.VISIBLE);
			}
		}
	};

	/** Handles data for jpeg picture */
	PictureCallback jpegCallback = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera camera) {
			if(data!=null){
				bmp=BitmapFactory.decodeByteArray(data,0,data.length);
				findViewById(R.id.img).setVisibility(View.VISIBLE);
				((ImageView)findViewById(R.id.img)).setImageBitmap(bmp);
				findViewById(R.id.preview).setVisibility(View.GONE);

				if(pg!=null)
					pg.dismiss();
				ok_button.setVisibility(View.VISIBLE);
				click_button.setVisibility(View.GONE);
				try_again_button.setVisibility(View.VISIBLE);
			}
		}
	};

	public void saveImage(){
		FileOutputStream out;
		try {
			File file=new File(Environment.getExternalStorageDirectory()+"temp.jpg");
			if(!file.exists()) file.createNewFile();
			out = new FileOutputStream(file);
			bmp.compress(CompressFormat.JPEG, 90, out);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Take Picture

To take the picture, we call takePicture() method of Camera. takePicture() is asynchronous method so we pass series of callbacks like ShutterCallback and PictureCallback (RawCallback & JPEGCallback).

ShutterCallback is a callback for image capture moment.
Raw PictureCallback is a callback for raw image data.
JPEG PictureCallback is a callback for JPEG encoding image data.

It’s upto you to do something with the data such as save it on SD card.

preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);

Saving picture on SD card

public void saveImage(){
	FileOutputStream out;
	try {
		File file=new File(Environment.getExternalStorageDirectory()+"temp.jpg");
		if(!file.exists()) file.createNewFile();
		out = new FileOutputStream(file);
		bmp.compress(CompressFormat.JPEG, 90, out);
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (Exception e) {
		e.printStackTrace();
	}
}

Finally, please don’t forgot to add following permissions in AndroidManifest.xml which we always forget :-) .

    <uses-permission android:name="android.permission.CAMERA"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

Google developing Android powered Home entertainment system

February 10th, 2012 No comments

According to The Wall Street Journal, Google is in the process of developing a home entertainment system based on Android and controlled by Android devices. The product appears to be similar to what Apple offers with its Apple TV and AirPlay service, and will allow users to stream music and video throughout their homes wirelessly.

Google has already attempted to break into the home entertainment business with its Google TV product, however, this new device is said to be built under Google’s own brand and will be marketed as such (Google TV devices are made and branded by outside companies like Logitech and Sony).

Google has been working on home automation for a while now home entertainment system would be a logical next step to a fully smart home. The home automation stuff that Google showed off at Google I/O in the past has yet to make it to the market.

So, droid is now trying to enter in your home too :-) .

Google Chrome Now on Android!!

February 10th, 2012 No comments

Well good news for android users. Google announced the Google Chrome for its users and it’s being made available immediately as a beta release for phones and tablets running Ice Cream Sandwich 4.0.

Browse fast on your Android smartphone or tablet, and bring your personalized Chrome experience with you anywhere you go.

Google says that the long-term plan is to make Chrome Android’s default browser, and everything we’ve seen here suggests that’s the right move. :-) In the meantime, it’ll be a free Android Market download, where it’ll install side by side with your existing browser.

Download google chrome here.


Google Chrome for Android 4.0 ICS



Categories: Android, News Tags: , ,

Android Animations

February 10th, 2012 No comments

Android provides two mechanisms that you can use to create simple animations:
Tweened animation , in which you tell Android to perform a series of simple transformations (position, size, rotation, and so on) to the content of a View; and Frame-By-Frame animation, which loads a series of Drawable resources one after the other. Both animation types can be used in any View object to provide simple rotating timers, activity icons, and other useful UI elements

1. Tweened Animation

Android can perform simple visual transformations for you, including straight line motion, size change, and transparency change, on the contents of a View object. These transformations are represented by the following classes:

  • AlphaAnimation (transparency changes)
  • RotateAnimation (rotations)
  • ScaleAnimation (growing or shrinking)
  • TranslateAnimation (position changes)

This animations can be highly customized and combined, for example we can set the speed, delay, acceleration, duration of animations, then group them together in an AnimationSet.

The animations can be defined in XMl or by code. Defining in xml is much more clear, but you can not set animation parameters dynamically.

The animation XML files should be created in the res/anim folder and can be accessed using R.anim.animation_name.

Project setup

We are going to load our animations for a ImageView used in an activity – so set up a new Android project. Add a ImageView to your main.xml

<?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">

	<ImageView android:id="@+id/iv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/icon"
      />

</LinearLayout>


Create a new Activity named AnimationActivity

package com.mobisys.android.twin_animation_ex;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
public class TwinAnimationActivity extends Activity {
 /** Called when the activity is first created. */
 @Override public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 final ImageView iv = (ImageView) findViewById(R.id.iv1);
 LinearLayout layout = (LinearLayout) findViewById(R.id.root);
 }
}


Alpha Animations

Alpha animations allows us to create fade-in/fade-out effects.
All animations are stored in res/anim so we create a new xml file named alpha.xml there.

Attributes:

android:fromAlpha
Float. Starting opacity offset, where 0.0 is transparent and 1.0 is opaque.
android:toAlpha
Float. Ending opacity offset, where 0.0 is transparent and 1.0 is opaque.


<?xml version="1.0" encoding="utf-8"?>

<alpha
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:fromAlpha="1.0"
 android:toAlpha="0.2"
 android:duration="4000" />


Note : The file must have a single root element: either an <alpha>, <scale>, <translate>, <rotate>, or <set> element that holds a group (or groups) of other animation elements (even nested <set> elements).

Change the activity to load the animation from the xml file and start the animation

package com.mobisys.android.animation_demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

public class AnimationActivity extends Activity {
    /** Called when the activity is first created. */
	ImageView imageView;
	Animation a;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        imageView=(ImageView)findViewById(R.id.iv1);
        a = AnimationUtils.loadAnimation(this, R.anim.alpha);
        a.reset();
        imageView.startAnimation(a);

    }
}


Rotate Animations

A rotation animation.

Attributes:

android:fromDegrees
Float. Starting angular position, in degrees.
android:toDegrees
Float. Ending angular position, in degrees.
android:pivotX
Float or percentage. The X coordinate of the center of rotation. Expressed either: in pixels relative to the object’s left edge (such as “5″), in percentage relative to the object’s left edge (such as “5%”), or in percentage relative to the parent container’s left edge (such as “5%p”).
android:pivotY
Float or percentage. The Y coordinate of the center of rotation. Expressed either: in pixels relative to the object’s top edge (such as “5″), in percentage relative to the object’s top edge (such as “5%”), or in percentage relative to the parent container’s top edge (such as “5%p”).

Add a new xml file to res/anim named rotate.xml

<?xml version="1.0" encoding="utf-8"?>

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
	 android:fromDegrees="0"
	 android:toDegrees="360"
	 android:pivotX="50%"
	 android:pivotY="50%"
	 android:duration="4000" />


Replace the alpha rotation with the new rotation animation in your activity.

Animation a = AnimationUtils.loadAnimation(this, R.anim.rotate);


Scale Animations

A resizing animation. You can specify the center point of the image from which it grows outward (or inward) by specifying pivotX and pivotY.

Attributes:

android:fromXScale
Float. Starting X size offset, where 1.0 is no change.
android:toXScale
Float. Ending X size offset, where 1.0 is no change.
android:fromYScale
Float. Starting Y size offset, where 1.0 is no change.
android:toYScale
Float. Ending Y size offset, where 1.0 is no change.
android:pivotX
Float. The X coordinate to remain fixed when the object is scaled.
android:pivotY
Float. The Y coordinate to remain fixed when the object is scaled.

Create another XML file in res/anim named scale.xml

<?xml version="1.0" encoding="utf-8"?>
<scale xmlns:android="http://schemas.android.com/apk/res/android"

            android:fromXScale="3.0"
            android:toXScale="1.0"
            android:fromYScale="3.0"
            android:toYScale="1.0"
            android:pivotX="50%"
            android:pivotY="50%"
            android:duration="4000" />


Load the animation in your activity.

Animation a = AnimationUtils.loadAnimation(this, R.anim.scale);


Translate Animations

A vertical and/or horizontal motion. Supports the following attributes in any of the following three formats: values from -100 to 100 ending with “%”, indicating a percentage relative to itself; values from -100 to 100 ending in “%p”, indicating a percentage relative to its parent; a float value with no suffix, indicating an absolute value.

Attributes:

android:fromXDelta
Float or percentage. Starting X offset. Expressed either: in pixels relative to the normal position (such as “5″), in percentage relative to the element width (such as “5%”), or in percentage relative to the parent width (such as “5%p”).

android:toXDelta
Float or percentage. Ending X offset. Expressed either: in pixels relative to the normal position (such as “5″), in percentage relative to the element width (such as “5%”), or in percentage relative to the parent width (such as “5%p”).

android:fromYDelta
Float or percentage. Starting Y offset. Expressed either: in pixels relative to the normal position (such as “5″), in percentage relative to the element height (such as “5%”), or in percentage relative to the parent height (such as “5%p”).

android:toYDelta
Float or percentage. Ending Y offset. Expressed either: in pixels relative to the normal position (such as “5″), in percentage relative to the element height (such as “5%”), or in percentage relative to the parent height (such as “5%p”).

Create translate.xml in res/anim

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:fillAfter="true">

	<translate android:fromXDelta="0"
	    android:toXDelta="30"
	    android:duration="4000"
	    android:fillAfter="true"/>

	<translate android:toYDelta="100"
        android:fillAfter="true"
        android:duration="4000"
        android:startOffset="4000"/>
 </set>


here <set>: A container that holds other animation elements (<alpha>, <scale>, <translate>, <rotate>) or other <set> elements.(i.e <set> contains multiple animation elements)

and android:fillAfter : When set to true, the animation transformation is applied after the animation is over.

Replace the animation in your activity

Animation a = AnimationUtils.loadAnimation(this, R.anim.translate);


2. Frame By Frame Animation

An object used to create frame-by-frame animations, defined by a series of Drawable objects, which can be used as a View object’s background.

The simplest way to create a frame-by-frame animation is to define the animation in an XML file, placed in the res/anim, and set it as the background to a View object. Then, call start() to run the animation.

An AnimationDrawable defined in XML consists of a single <animation-list> element, and a series of nested tags. Each item defines a frame of the animation.

Firstly,we will define ImageView in main.xml

<?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"
    android:gravity="center">

    <ImageView android:id="@+id/img"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"/>

</LinearLayout>


spin_animation.xml file in res/anim/ folder:

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
	android:oneshot="false">
    <item android:drawable="@drawable/blue_baloon" android:duration="1000" />
    <item android:drawable="@drawable/orange_baloon" android:duration="1000" />
    <item android:drawable="@drawable/red_baloon" android:duration="1000" />

</animation-list>



You can download images here

Here is the code to load and play this animation.

package com.mobisys.android.frame_by_frame;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.widget.ImageView;

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

    	ImageView img=(ImageView)findViewById(R.id.img);
        img.setBackgroundResource(R.anim.spin_animation);
        AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();
        frameAnimation.start();
    }
}


Here don’t start animation until window’s focus get changed. So never start the animation in onCreate().
So for that override the method onWindowFocusChanged() and start animation in this method.

Run the application. :-)

Android Fonts

January 28th, 2012 No comments

Every Android device comes with a collection of standard fonts: Droid Sans, Droid Sans Mono and Droid Serif. They were designed to be optimal for mobile displays, so these are the three fonts you will be working with most of the time and they can be styled using a handful of XML attributes. You might, however, see the need to use custom fonts for special purposes. We’ll be taking a look at that as well.

Font Style Attributes

In the following section we’re going to examine the different XML attributes that you can use to style components with text.

Typeface

As stated in the overview, there are three different default typefaces which are known as the Droid family of fonts: sans, monospace and serif. You can specify any one of them as the value for the android:typeface attribute in the XML declaration of a component that supports text styling, such as TextView. Here’s an example of all three typefaces in action:

<?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"/>

	<TextView android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="I am Normal"
	    android:layout_marginLeft="8dp"
	    android:layout_marginTop="8dp"/>

    <TextView android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="I am Serif"
	    android:typeface="serif"
	    android:layout_marginLeft="8dp"
	    android:layout_marginTop="8dp"/>

	<TextView android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="I am Sans"
	    android:typeface="sans"
	    android:layout_marginLeft="8dp"
	    android:layout_marginTop="8dp"/>    

    <TextView android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="I am Monospace"
	    android:typeface="monospace"
	    android:layout_marginLeft="8dp"
	    android:layout_marginTop="8dp"/>
</LinearLayout>


In addition to the above, there is another attribute value named “normal” which defaults to the sans typeface.

DROID family & normal font


Using Custom Fonts

We’ll use Garamond.TTF font for demonstration purposes. Download it and place the TTF file in the ./assets directory (create it if it doesn’t exist yet).
We’re going to use a basic layout file with a TextView, marked with an id of “custom_font” so we can access it in our code.

<?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:id="@+id/custom_font"
	 	android:layout_width="fill_parent"
	        android:layout_height="wrap_content"
	        android:text="This is garamond Font"/>


Open your main activity file and insert this into the onCreate() method:

TextView t=(TextView)findViewById(R.id.custom_font);
        Typeface font=Typeface.createFromAsset(getAssets(), "Garamond.TTF");
        t.setTypeface(font);


The Typeface class contains a static builder method createFromAsset, which takes an AssetManager as its first parameter and a path to the file in the second argument. We’re handing it the default asset manager and the name of the font file because it’s located in the root of the “assets” folder. Once we’ve got an instance of our custom typeface, all that’s left is a call to TextView’s setTypeface() method.

Custom Font

>

Text Style

The android:textStyle attribute can be used to put emphasis on text. The possible values are: normal, bold, italic. You can also specify bold|italic.

<TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="This is bold!"
            android:textStyle="bold"  />


Text Style


Text Size

android:textSize specifies the font size. Its value must consist of two parts: a floating-point number followed by a unit. Available units are: sp (scaled pixels), px (pixels), dp (density-independent pixels), in (inches), mm (millimeters). It is generally a good practice to use the sp unit so that it will be consistent across all screen resolutions.

<TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="15sp is the 'normal' size."
        android:textSize="15sp" />



Text Size


Text Color

The android:textColor attribute’s value is a hexadecimal RGB value.

    <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="A light blue color."
            android:textColor="#00ccff"
            />



SMS Messaging in Android

January 26th, 2012 No comments

In this article, we take a look at how you can programmatically send and receive SMS messages in your Android applications. The good news for Android developers is that you don’t need a real device to test out SMS messaging – the free Android emulator provides the capability to do so.

Sending SMS Messages

Create project named com.mobisys.android.sms_messaging having activity SMSActivity in it.

In the AndroidManifest.xml file, add the two permissions – SEND_SMS and RECEIVE_SMS:


<uses-permission android:name="android.permission.SEND_SMS"/>

    <uses-permission android:name="android.permission.RECEIVE_SMS"/>


In the main.xml file located in the res/layout folder, add the following code so that the user can enter a phone number as well as a message to send:

<?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="Enter the phone number of recipient"
        />
    <EditText
        android:id="@+id/txtPhoneNo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Message"
        />
    <EditText
        android:id="@+id/txtMessage"
        android:layout_width="fill_parent"
        android:layout_height="150px"
        android:gravity="top"
        />
    <Button
        android:id="@+id/btnSendSMS"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send SMS"
        />
</LinearLayout>


The above code creates the UI :

Creating the UI for sending SMS messages


Next, in the SMSActivity, when the user clicks on Button, we will check to see that the phone number of the recipient and the message is entered before we send the message using the sendSMS() function.

package com.mobisys.android.sms_messaging;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SMSActivity extends Activity
{
    Button btnSendSMS;
    EditText txtPhoneNo;
    EditText txtMessage;

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

        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
        txtMessage = (EditText) findViewById(R.id.txtMessage);

        btnSendSMS.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                String phoneNo = txtPhoneNo.getText().toString();
                String message = txtMessage.getText().toString();
                if (phoneNo.length()>0 && message.length()>0)
                    sendSMS(phoneNo, message);
                else
                    Toast.makeText(getBaseContext(),
                        "Please enter both phone number and message.",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

The sendSMS() function is defined as follows:


private void sendSMS(String phoneNumber, String message)
    {
        PendingIntent pi = PendingIntent.getActivity(this, 0,
            new Intent(this, SMSActivity.class), 0);
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, pi, null);
    }


To send an SMS message, you use the SmsManager class. Unlike other classes, you do not directly instantiate this class; instead you will call the getDefault() static method to obtain an SmsManager object. The sendTextMessage() method sends the SMS message with a PendingIntent. The PendingIntent object is used to identify a target to invoke at a later time. For example, after sending the message, you can use a PendingIntent object to display another activity. In this case, the PendingIntent object (pi) is simply pointing to the same activity , so when the SMS is sent, nothing will happen.

If you need to monitor the status of the SMS message sending process, you can actually use two PendingIntent objects together with two BroadcastReceiver objects, like this:


private void sendSMS(String phoneNumber, String message)
    {
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);

        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));

        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(DELIVERED));        

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
    }


The above code uses a PendingIntent object (sentPI) to monitor the sending process. When an SMS message is sent, the first BroadcastReceiver‘s onReceive event will fire. This is where you check the status of the sending process. The second PendingIntent object (deliveredPI) monitors the delivery process. The second BroadcastReceiver‘s onReceive event will fire when an SMS is successfully delivered.

You can now test the application.


Sending an SMS


Above figure shows how you can send an SMS message from one emulator to another; simply use the target emulator’s port number (shown in the top left corner of the window) as its phone number. When an SMS is sent successfully, it will display a “SMS sent” message. When it is successfully delivered, it will display a “SMS delivered” message. Note that for testing using the emulator, when an SMS is successfully delivered, the “SMS delivered” message does not appear; this only works for real devices.

Following figure shows the SMS message received on the recipient emulator. The message first appeared in the notification bar (top of the screen). Dragging down the notification bar reveals the message received. To view the entire message, click on the message.

SMS message received by the Android Emulator



Receiving SMS Messages

Besides programmatically sending SMS messages, you can also intercept incoming SMS messages using a BroadcastReceiver object.
To see how to receive SMS messages from within your Android application, in the AndroidManifest.xml file add the element so that incoming SMS messages can be intercepted by the SmsReceiver class:

        <receiver android:name=".SmsReceiver">
            <intent-filter>
                <action android:name=
                    "android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>


Add a new class file to your project and name it as SmsReceiver.java

In the SmsReceiver class, extend the BroadcastReceiver class and override the onReceive() method:

package com.mobisys.android.sms_messaging;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class SmsReceiver extends BroadcastReceiver
{
	@Override
	public void onReceive(Context context, Intent intent)
       {
	}
}


When SMS messages are received, the onCreate() method will be invoked. The SMS message is contained and attached to the Intent object (intent – the second parameter in the onReceive() method) via a Bundle object. The messages are stored in an Object array in the PDU format. To extract each message, you use the static createFromPdu() method from the SmsMessage class. The SMS message is then displayed using the Toast class:

package com.mobisys.android.sms_messaging;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String str = "";
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                str += "SMS from " + msgs[i].getOriginatingAddress();
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "\n";
            }
            //---display the new SMS message---
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        }                      

	}

}


All you need to do is to select each emulator and deploy the application onto each one.

Figure shows that when you send an SMS message to another emulator instance (port number 5554), the message is received by the target emulator and displayed via the Toast class.

Sending and receiving SMS messages using the Android emulators


Download Source code

Click here to download

Android Layouts : LinearLayout and RelativeLayout

January 20th, 2012 1 comment

In this tutorial we will be discussing about the different view layouts in an android mobile application. The six different layouts are

1. Linear Layout
2. Relative Layout
3. Table Layout
4. Grid View
5. Tab Layout
6. List View

Android allows you to create view layouts using simple XML file. All the layouts must be placed in /res/layout folder.

Android Layout Directory


Mostly in many applications we use “Linear Layout” and “relative layout” only. So we will learn these layouts below.

Linear Layout

In a linear layout, like the name suggests, all the elements are displayed in a linear fashion, either Horizontally or Vertically and this behavior is set in android:orientation which is an attribute of the node LinearLayout.
i.e.
Example of Vertical layout

<LinearLayout android:orientation="vertical"> .... </LinearLayout>


Example of Horizontal layout

<LinearLayout android:orientation="horizontal"> .... </LinearLayout>

Let’s create project:
1) Create a new project File -> New -> Android Project
2) Create linear_layout.xml in res/layout and insert following

<?xml version="1.0" encoding="utf-8"?>
<!-- Parent linear layout with vertical orientation -->
<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="Email:" />

  <EditText android:layout_width="fill_parent"
     		android:layout_height="wrap_content"/>             

  <Button android:layout_width="fill_parent"
		    android:layout_height="wrap_content"
		    android:text="Login"/>

  <!-- Child linear layout with horizontal orientation -->
  <LinearLayout android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:background="#2a2a2a"
            android:layout_marginTop="10dp">

  <TextView android:layout_width="wrap_content"
  			android:layout_height="wrap_content"
            android:text="Home"
            android:gravity="center"/>

  <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="About"
            android:paddingLeft="8dp"
            android:gravity="center"/>   

  </LinearLayout>

</LinearLayout>


Linear Layout Output

Here Email TextView, EditText and Login Button are vertical in layout. whereas Home and about are in horizontal layout.

Relative Layout

In a relative layout every element arranges itself relative to other elements or a parent element.

Relative To Container

These properties will layout elements relative to the parent container.

1) android:layout_alignParentBottom – Places the bottom of the element on the bottom of the container

2) android:layout_alignParentLeft – Places the left of the element on the left side of the container

3) android:layout_alignParentRight – Places the right of the element on the right side of the container

4) android:layout_alignParentTop – Places the element at the top of the container

5) android:layout_centerHorizontal – Centers the element horizontally within its parent container

6) android:layout_centerInParent – Centers the element both horizontally and vertically within its container

7) android:layout_centerVertical – Centers the element vertically within its parent container

Example


<RelativeLayout
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<Button
 		android:id="@+id/button01"
 		android:text="Top Button Horizontally center"
 		android:layout_alignParentTop="true"
 		android:layout_width="wrap_content"
 		android:textSize="10sp"
 		android:layout_centerHorizontal="true"
 		android:layout_height="wrap_content" />

	<Button
 		android:id="@+id/button02"
 		android:text="Bottom Button Horizontally center"
 		android:layout_alignParentBottom="true"
 		android:layout_width="wrap_content"
 		android:textSize="10sp"
 		android:layout_centerHorizontal="true"
 		android:layout_height="wrap_content" />

 	<Button
 		android:id="@+id/button03"
 		android:text="Left Button Vertically center"
 		android:layout_width="wrap_content"
 		android:textSize="10sp"
 		android:layout_alignParentLeft="true"
 		android:layout_centerVertical="true"
 		android:layout_height="wrap_content" />	

<Button
 		android:id="@+id/button04"
 		android:text="Right Button Vertically center"
 		android:layout_width="wrap_content"
 		android:layout_alignParentRight="true"

 		android:layout_centerVertical="true"
 		android:textSize="10sp"
 		android:layout_height="wrap_content" />
</RelativeLayout>



Relative Layout Output-1


Relative To Other Elements

These properties allow you to layout elements relative to other elements on screen.

1) android:layout_above – Places the element above the specified element

2) android:layout_below – Places the element below the specified element

3) android:layout_toLeftOf – Places the element to the left of the specified element

4) android:layout_toRightOf – Places the element to the right of the specified element

Example


<RelativeLayout
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<Button
 		android:id="@+id/button01"
 		android:text="Button1"
 		android:layout_width="wrap_content"
 		android:layout_height="wrap_content" />
	<Button
 		android:id="@+id/button02"
 		android:layout_width="wrap_content"
 		android:layout_height="wrap_content"
 		android:layout_toRightOf="@id/button01"
 		android:layout_marginLeft="8dp"
 		android:text="To the RightOf Button1"/>
 	<Button
 		android:id="@+id/button03"
 		android:layout_width="wrap_content"
 		android:layout_height="wrap_content"
 		android:layout_below="@id/button01"
 		android:layout_alignParentRight="true"
 		android:text="Button 2"/>
 	<Button
 		android:id="@+id/button04"
 		android:layout_width="wrap_content"
 		android:layout_height="wrap_content"
 		android:layout_below="@id/button01"
 		android:layout_toLeftOf="@id/button03"
		android:text="To Left of Button 2"/>

</RelativeLayout>


Relative Layout output-2


Alignment With Other Elements

These Properties allow you to specify how elements are aligned in relation to other elements.

1) android:layout_alignBaseline – Aligns baseline of the new element with the baseline of the specified element

2) android:layout_alignBottom – Aligns the bottom of new element in with the bottom of the specified element

3) android:layout_alignLeft – Aligns left edge of the new element with the left edge of the specified element

4) android:layout_alignRight – Aligns right edge of the new element with the right edge of the specified element

5) android:layout_alignTop – Places top of the new element in alignment with the top of the specified element

Example


<RelativeLayout
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<Button
 		android:id="@+id/button01"
 		android:layout_width="wrap_content"
 		android:layout_height="wrap_content"
		android:text="Button-2 right boundary aligned with this button"/>
	<Button
 		android:id="@+id/button02"
 		android:layout_width="wrap_content"
 		android:layout_height="wrap_content"
 		android:text="Button-2"
 		android:layout_below="@id/button01"
 		android:layout_alignRight="@+id/button01"/>
</RelativeLayout>


UI Component: WebView

January 20th, 2012 No comments

A View that displays web pages. This class is the basis upon which you can roll your own web browser or simply display some online content within your Activity. It uses the WebKit rendering engine to display web pages.

In this demo, we get to view a web address in a totally different way by sidestepping the default browser and creating our own custom webviewer.

The key to creating the custom webviewer is the MyWebViewClient class that extends the WebViewClient class. With its key method shouldOverrideUrlLoading(view,url) that gives control to application when a new url is loaded in the provided view.

Sample Example

1) Create a new project/Activity called UIActivity.

2) We will have EditText in which URL to be entered, Button and WebView.

So Open the layout file. Insert 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"
    >

    <LinearLayout
    	android:orientation="horizontal"
    	android:layout_width="fill_parent"
    	android:layout_height="wrap_content">

	    <EditText
	    android:id="@+id/url"
	    android:layout_height="wrap_content"
	    android:layout_width="wrap_content"
	    android:lines="1"
	    android:layout_weight="1.0"
	    android:hint="http://"/>

	    <Button
	    android:id="@+id/go_button"
	    android:layout_height="wrap_content"
	    android:layout_width="wrap_content"
	    android:text="go"
	    />

    </LinearLayout>

	<WebView
		android:id="@+id/webview_compontent"
	    android:layout_width="fill_parent"
	    android:layout_height="fill_parent"
	/>
</LinearLayout>


3) Now open the UIActivity.java file. At the top of the class, instantiate a WebView object:

                private WebView webView;
		private EditText urlField;


Then add the following at the end of the onCreate() method:

                        webView  = (WebView) findViewById(R.id.webview_compontent);
		        urlField = (EditText)findViewById(R.id.url);

((Button)findViewById(R.id.go_button)).setOnClickListener(new View.OnClickListener(){

					@Override
					public void onClick(View v) {

						webView.loadUrl(urlField.getText().toString());

					}
		        });


This captures the WebView we created in our layout.
Here we can load a page, but as soon as we click a link, the default Android web browser handles the Intent, instead we will be handling actions in our own WebView.

4) Because we’re accessing the internet, we need to add the appropriate permissions to the Android manifest file. So open the AndroidManifest.xml file and, add the following as a child of the element:

<uses-permission android:name="android.permission.INTERNET" />


So now we’ll override the WebViewClient to enable us to handle our own URL loading.

In the UIActivity, add this nested private class:

private class MyWebViewClient extends WebViewClient {
	        @Override
	        public boolean shouldOverrideUrlLoading(WebView view, String url) {
	            view.loadUrl(url);
	            return true;
	        }
	    }


Now, in the onCreate() method, set an instance of the HelloWebViewClient as our WebViewClient:

webView.setWebViewClient(new MyWebViewClient());



This line should immediately follow the initialization of our WebView object.

What we’ve done is create a WebViewClient that will load any URL selected in our WebView in the same WebView. You can see this in the shouldOverrideUrlLoading() method, above—it is passed the current WebView and the URL, so all we do is load the URL in the given view. Returning true says that we’ve handled the URL ourselves.

5) Run the application.

UI Components: Part-1

January 19th, 2012 3 comments

There are several UI components are exist. We will learn some basic components.

Button

Buttons can be pressed, or clicked, by the user to perform an action.
we can create Button by writing following code:

<Button
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:id="@+id/button"
     android:text="Click to Perform Action"/>



Attach listeners inside your activity “onCreate()” method to perform action,


        ((Button)findViewById(R.id.button)).setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v) {
				//Perform action here
			}
		});


TextView, EditText

Write layout file containing EditText with inputType set to to “text“, “number” and “textPassword” for alpha-numeric, numeric and password text respectively. Also add TextView which will be not editable. Default inputType of EditText is “text“.


<?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"
    />

  <EditText android:id="@+id/edittext01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Text"/>

  <EditText android:id="@+id/edittext02"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:hint="Number"/>

    <EditText android:id="@+id/edittext03"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="textPassword"
    android:hint="Text password"/>  

</LinearLayout>


Getting Text value of EditText

str=text.getText().toString();
Toast.makeText(UIActivity.this,str, Toast.LENGTH_SHORT).show();


CheckBox

For CheckBox we can have

<CheckBox
        android:id="@+id/chkAnd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android" />


and to perform action

CheckBox ChkBx =(CheckBox)findViewById(R.id.chkAnd);

        ChkBx.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub

			} });


RadioGroup and RadioButtons

This class is used to create a multiple-exclusion scope for a set of radio buttons. Checking one radio button that belongs to a radio group unchecks any previously checked radio button within the same group.

Intially, all of the radio buttons are unchecked. While it is not possible to uncheck a particular radio button, the radio group can be cleared to remove the checked state.

The selection is identified by the unique id of the radio button as defined in the XML layout file.

xml file contains:

<?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="wrap_content"
	android:layout_height="wrap_content"
	android:text="RadioGroup"/>

<RadioGroup android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:orientation="vertical"
	android:id="@+id/radiogroup">

<RadioButton android:id="@+id/radiobutton1"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:text="radio1" >
</RadioButton>

<RadioButton android:id="@+id/radiobutton2"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:text="radio2">
</RadioButton>

<RadioButton android:id="@+id/radiobutton3"
	android:layout_width="wrap_content"
 	android:layout_height="wrap_content"
 	android:text="radio3">
 </RadioButton>

</RadioGroup>

</LinearLayout>


Whenever you will select radio button, the related messsage will be displayed
Note: You need to implement RadioGroup.OnCheckedChangeListener in main activity
i.e

package com.mobisys.android.ui_components;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class UIActivity extends Activity implements
RadioGroup.OnCheckedChangeListener{
    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        RadioGroup rg = (RadioGroup) findViewById(R.id.radiogroup);
        rg.setOnCheckedChangeListener(this);
    }

    public void onCheckedChanged(RadioGroup group, int checkedId) {
    	String radioButtonSelected = "";
    	switch (checkedId) {

        case R.id.radiobutton1 : radioButtonSelected = "radiobutton1";
                         	              break;
        case R.id.radiobutton2 : radioButtonSelected = "radiobutton2";
      		                      break;
        case R.id.radiobutton3 : radioButtonSelected = "radiobutton3";
      		                      break;

        }
    	Toast.makeText(UIActivity.this,radioButtonSelected+" Selected", Toast.LENGTH_SHORT).show();
    }
  }



ImageView

Displays an arbitrary image, such as an icon. The ImageView class can load images from various sources (such as resources or content providers), takes care of computing its measurement from the image so that it can be used in any layout manager.

Setting image from Resource

Download the following folder and copy the images in res/drawable folder
images

xml contains:

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

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ok" />

    <Button
        android:id="@+id/btnChangeImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Image" />

</LinearLayout>


When we click Button it changes the image as specified in setImageResource().

package com.mobisys.android.ui_components;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class UIActivity extends Activity{
    /** Called when the activity is first created. */
	ImageView image;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ((Button)findViewById(R.id.btnChangeImage)).setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {

				image = (ImageView) findViewById(R.id.imageView1);
				image.setImageResource(R.drawable.no);
			}

        });
}
}


Setting image from Bitmap

All this below code does is load the image icon.png from sdcard. The BitmapFactory creates a bitmap object with this image and we use the myImage.setImageBitmap() method to update the ImageView component.

You can use the above xml.

And for setting the image using Bitmap you can have

package com.mobisys.android.ui_components;

import java.io.File;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class UIActivity extends Activity{
    /** Called when the activity is first created. */
	ImageView image;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ((Button)findViewById(R.id.btnChangeImage)).setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				File imgFile = new  File(Environment.getExternalStorageDirectory()+"/Images/icon.png");

				if(imgFile.exists()){

				    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

				    ImageView myImage = (ImageView) findViewById(R.id.imageView1);
				    myImage.setImageBitmap(myBitmap);

				}

			}

        });
}
}


Spinner

Spinner is a widget similar to a drop-down list for selecting items.
you’ll create a simple spinner widget that contains a list of planets.

main.xml contains:

?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:text="@string/planet_prompt"
    />
    <Spinner
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:prompt="@string/planet_prompt"
    />
</LinearLayout>


Create a strings.xml file in res/values/ and enter the following:

<string name="planet_prompt">Choose a planet</string>
    <string-array name="planets_array">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
        <item>Jupiter</item>
        <item>Saturn</item>
        <item>Uranus</item>
        <item>Neptune</item>
    </string-array>


and our java code will look like:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
            this, R.array.planets_array, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
}


output screens:


Toggle Button

Displays checked/unchecked states as a button with a “light” indicator and by default accompanied with the text “ON” or “OFF“.

layout file contains:

<?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" />

<ToggleButton android:id="@+id/togglebutton"
android:layout_width="150px"
android:layout_height="50px"
android:textOn="ON"
android:textOff="OFF" />

</LinearLayout>


and java code will look like:

	public class UIActivity extends Activity
	{
		ToggleButton tb;

		public void onCreate(Bundle savedInstanceState)
		{
				super.onCreate(savedInstanceState);
		        setContentView(R.layout.main);

		        tb = (ToggleButton) findViewById(R.id.togglebutton);
		        tb.setOnCheckedChangeListener(new OnCheckedChangeListener(){

					@Override
					public void onCheckedChanged(CompoundButton button,
							boolean isChecked) {

						if(isChecked)
							Toast.makeText(UIActivity.this, "Toggle Button is on", Toast.LENGTH_LONG).show();
						else
							Toast.makeText(UIActivity.this, "Toggle Button is off", Toast.LENGTH_LONG).show();;
					}

		        });

	}
	}



Toggle Off:

Toggle On: