Archive

Archive for February, 2012

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 1 comment

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. :-)