Thursday, December 22, 2011

Android Animation App - Bouncing Ball

So looking for play with animation stuff.. good!! you are on right place  :)
today we are going to learn how to create simple android animation app.
so in this application we will create Background View and Ball programatically which will jump.

let's began the code, first of all we need to create simple android app having single Activity
name is :
BouncingBallActivity.java


package com.mytest;

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

public class BouncingBallActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        
        View bouncingBallView = new BouncingBallView(this);
        setContentView(bouncingBallView);
    }
}

Now we need to create a View programatically [we will not using any xml file]
here we go..
BouncingBallView.java
  
package com.mytest;
  
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.KeyEvent;
import android.view.View;
   
public class BouncingBallView extends View {
   private int xMin = 0;          // This view's bounds
   private int xMax;
   private int yMin = 0;
   private int yMax;
   private float ballRadius = 40; // Ball's radius
   private float ballX = ballRadius + 20;  // Ball's center (x,y)
   private float ballY = ballRadius + 40;
   private float ballSpeedX = 5;  // Ball's speed (x,y)
   private float ballSpeedY = 3;
   private RectF ballBounds;      // Needed for Canvas.drawOval
   private Paint paint;           // The paint (e.g. style, color) used for drawing
   
   // Constructor
   public BouncingBallView(Context context) {
      super(context);
      ballBounds = new RectF();
      paint = new Paint();
      
      //to enable keypad
      this.setFocusable(true);
      this.requestFocus();
   }
  
   // Called back to draw the view. Also called by invalidate().
   @Override
   protected void onDraw(Canvas canvas) {
      // Draw the ball
      ballBounds.set(ballX-ballRadius, ballY-ballRadius, ballX+ballRadius, ballY+ballRadius);
      paint.setColor(Color.GREEN);
      canvas.drawOval(ballBounds, paint);
        
      // Update the position of the ball, including collision detection and reaction.
      update();
  
      // Delay
      try {  
         Thread.sleep(60);  
      } catch (InterruptedException e) { }
      
      invalidate();  // Force a re-draw
   }
   
   // Detect collision and update the position of the ball.
   private void update() {
      // Get new (x,y) position
     // ballX += ballSpeedX;
      ballY += ballSpeedY;
      // Detect collision and react
      if (ballX + ballRadius > xMax) {
         ballSpeedX = -ballSpeedX;
         ballX = xMax-ballRadius;
      } else if (ballX - ballRadius < xMin) {
         ballSpeedX = -ballSpeedX;
         ballX = xMin+ballRadius;
      }
      if (ballY + ballRadius > yMax) {
         ballSpeedY = -ballSpeedY;
         ballY = yMax - ballRadius;
      } else if (ballY - ballRadius < yMin) {
         ballSpeedY = -ballSpeedY;
         ballY = yMin + ballRadius;
      }
   }
   
   // Called back when the view is first created or its size changes.
   @Override
   public void onSizeChanged(int w, int h, int oldW, int oldH) {
      // Set the movement bounds for the ball
      xMax = w-1;
      yMax = h-1;
   }
   
   // key-up event handler
   @Override
   public boolean onKeyUp(int keyCode, KeyEvent event) {
      switch (keyCode) {
         case KeyEvent.KEYCODE_DPAD_RIGHT: // Increase rightward speed
            ballSpeedX++;
            break;
         case KeyEvent.KEYCODE_DPAD_LEFT:  // Increase leftward speed
            ballSpeedX--;
            break;
         case KeyEvent.KEYCODE_DPAD_UP:    // Increase upward speed
            ballSpeedY--;
            break;
         case KeyEvent.KEYCODE_DPAD_DOWN:  // Increase downward speed
            ballSpeedY++;
            break;
         case KeyEvent.KEYCODE_DPAD_CENTER: // Stop
            ballSpeedX = 0;
            ballSpeedY = 0;
            break;
         case KeyEvent.KEYCODE_A:    // Zoom in
            // Max radius is about 90% of half of the smaller dimension
            float maxRadius = (xMax > yMax) ? yMax / 2 * 0.9f  : xMax / 2 * 0.9f;
            if (ballRadius < maxRadius) {
               ballRadius *= 1.05;   // Increase radius by 5%
            }
            break;
         case KeyEvent.KEYCODE_Z:    // Zoom out
            if (ballRadius > 20) {   // Minimum radius
               ballRadius *= 0.95;   // Decrease radius by 5%
            }
            break;
      }
      return true;  // Event handled
   }
   
   
}
at last our manifest file should look like this..
AndroidManifest.xml
  


    

    
        
            
                
                
            
        

    


output is like this

we have done great job on ma B'day!!   :D

cheers!!

I'd love to here your thoughts!

Monday, December 12, 2011

AlertBox in Android (Advance)

This is also simple Tutorial for Android Alert Box Dialog.

Few things we can do with this that cann't with Basic Tutorial like

  • We are adding the alert icon to Dialog box.
  • It shows the alert message as Basic does.
  • We can make decision whether cancel alert message or do some task

okay! so let's try this small app

 -------------------------------------------
App Name: AlertBoxAdvance
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: AlertBoxAdvance
-------------------------------------------

project structure is look like this


Note: you need to save below alert icon and put into drawable folder


AlertBoxAdvance.java
package com.rdc;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;

public class AlertBoxAdvance extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
        
    //create advance Alert dialog box
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure you want to exit this App?")
       .setCancelable(false)
       .setTitle("AlertBox")
       .setIcon(R.drawable.alert)
       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
               //finish the current activity
               AlertBoxAdvance.this.finish();
           }
        })
       .setNegativeButton("No", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
              //cancel the dialog box 
             dialog.cancel();
            }
        });
       AlertDialog alert = builder.create();
       alert.show();
        
    }
}

main.xml



AndroidManifest.xml

 

 
  
   
   
   
   
  

 


The output Screen will be like this..

You can download the complete source code zip file here : AlertBoxAdvance

cheers!!

I'd love to hear your thoughts!

Monday, December 5, 2011

AlertBox in Android (Basic)

This is the simple and very basic Tutorial for Android Alert Box Dialog.
Just create alert box and you can call it whenever you want in app

so let's try this small app

 -------------------------------------------
App Name: AlertBoxBasic
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: AlertBoxActivity
-------------------------------------------

 AlertBoxActivity.java

package com.rdc;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;

public class AlertBoxActivity extends Activity {   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //call alert box code to display dialog
        alertbox("Alert Box","Your Application has been started..");
    }
   
    //create alert dialog box
    protected void alertbox(String title, String mymessage) 
    { 
    new AlertDialog.Builder(this) 
       .setMessage(mymessage) 
      .setTitle(title) 
       .setCancelable(true) 
       .setNeutralButton("OK", 
          new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int whichButton){} 
          }) 
       .show(); 
    }
}

main.xml



AndroidManifest.xml





 
 
 
 





The output Screen will be like this..

You can download the complete source code zip file here : AlertBoxBasic

cheers!!

 I'd love to hear your thoughts!

Saturday, November 26, 2011

TabWidget in Android (Advance)

We already create simple Tab app in android check TabWidget in Android (Basic)
So today we will try to add some advance things.

like how to put Tabs at the Bottom in Android
load different pages on different Tabs.

so let's try this small app..

 -------------------------------------------
App Name: TabWidgetAdvance
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default TabActivity Name: ActivityTabWidget
-------------------------------------------


ActivityTabWidget.java

package com.rdc;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.TabHost;

public class ActivityTabWidget extends TabActivity {
 private TabHost mTabHost = null;
 private Intent ihome, imusic, iabout;

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

  //create tab host to add tabs
  mTabHost = getTabHost();

  
  LayoutInflater.from(this).inflate(R.layout.main,
    mTabHost.getTabContentView(), true);

  // create intents to load another page on Tabs
  ihome = new Intent(ActivityTabWidget.this, ActivityHome.class);
  imusic = new Intent(ActivityTabWidget.this, ActivityMusic.class);
  iabout= new Intent(ActivityTabWidget.this,ActivityAboutMe.class);

  // create tabs and add to TabHost

  mTabHost.addTab(mTabHost.newTabSpec("tab1")
    .setIndicator(" Home ")
    .setContent(ihome));

  mTabHost.addTab(mTabHost.newTabSpec("tab3")
    .setIndicator(" Music ")
    .setContent(imusic));

  mTabHost.addTab(mTabHost.newTabSpec("tab3")
    .setIndicator(" About Me ")
    .setContent(iabout));

  // set default selected tab
  mTabHost.setCurrentTab(0);

 }
}

now create three Activities Pages for Three different Tabs
ActivityHome.java
package com.rdc;

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

public class ActivityHome extends Activity {

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


ActivityMusic.java
package com.rdc;

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

public class ActivityMusic extends Activity {

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


ActivityAboutMe.java
package com.rdc;

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

public class ActivityAboutMe extends Activity {

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

}


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

  <FrameLayout
   android:id="@android:id/tabcontent"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:layout_weight="1">
   <TextView
    android:id="@+id/textview1"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"></TextView>
   <TextView
    android:id="@+id/textview2"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"></TextView>
   <TextView
    android:id="@+id/textview3"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"></TextView>
  </FrameLayout>
  <TabWidget
   android:id="@android:id/tabs"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:layout_weight="0"
   android:layout_marginBottom="-4dp">
  </TabWidget>
 </LinearLayout>
</TabHost>

now create three XML Pages for Three different Tabs
home.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:gravity="center_vertical"
 android:background="#A9A9A9">
 <TextView
  android:id="@+id/textView1"
  android:layout_height="wrap_content"
  android:layout_width="match_parent"
  android:text="Home"
  android:gravity="center_horizontal"
  android:textColor="#000000"></TextView>

</LinearLayout>

music.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:gravity="center_vertical"
 android:background="#A9A9A9">
 <TextView
  android:id="@+id/textView1"
  android:gravity="center_horizontal"
  android:layout_height="wrap_content"
  android:layout_width="match_parent"
  android:text="Music"
  android:textColor="#000000"></TextView>
</LinearLayout>


aboutme.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:gravity="center_vertical"
 android:background="#A9A9A9">
 <TextView
  android:id="@+id/textView1"
  android:gravity="center_horizontal"
  android:layout_height="wrap_content"
  android:layout_width="match_parent"
  android:text="About Me"
  android:textColor="#000000"></TextView>
</LinearLayout>


AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="10" />

 <application
  android:icon="@drawable/icon"
  android:label="@string/app_name">
  <activity
   android:name=".ActivityTabWidget"
   android:label="@string/app_name">
   <intent-filter>
   <action android:name="android.intent.action.MAIN" />
   <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>

  <activity
   android:name=".ActivityHome"
   android:label="@string/app_name">
   <intent-filter>
   <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>

  <activity
   android:name=".ActivityMusic"
   android:label="@string/app_name">
   <intent-filter>
   <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>

  <activity
   android:name=".ActivityAboutMe"
   android:label="@string/app_name">
   <intent-filter>
   <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>

 </application>
</manifest>

The app will start like this..


You can download the complete source code zip file here : TabWidgetAdvance

cheers!!

I'd love to hear your thoughts!

Tuesday, November 22, 2011

TabWidget in Android (Basic)

Today we will try Tab-Widget in Android , using we can develop Tab Bar apps.

Displays a list of tab labels representing each page in the parent's tab collection. The container object for this widget is TabHost .


We will create very simple app to do this work..

 -------------------------------------------
App Name: TabWidgetBasic
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default TabActivity Name: ActivityTabWidget
-------------------------------------------


ActivityTabWidget.java

package com.rdc;

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

public class ActivityTabWidget extends TabActivity {

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

  mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("TAB 1")
    .setContent(R.id.textview1));
  mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("TAB 2")
    .setContent(R.id.textview2));
  mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("TAB 3")
    .setContent(R.id.textview3));

  mTabHost.setCurrentTab(0);
  }
}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@android:id/tabhost"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">
 <LinearLayout
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:gravity="bottom">
  <TabWidget
   android:id="@android:id/tabs"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"></TabWidget>
  <FrameLayout
   android:id="@android:id/tabcontent"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">
   <TextView
    android:id="@+id/textview1"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:text="this is a tab"></TextView>
   <TextView
    android:id="@+id/textview2"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:text="this is another tab"></TextView>
   <TextView
    android:id="@+id/textview3"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:text="this is a third tab"></TextView>
  </FrameLayout>
 </LinearLayout>
</TabHost>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="10" />

 <application
  android:icon="@drawable/icon"
  android:label="@string/app_name">
  <activity
   android:name=".ActivityTabWidget"
   android:label="@string/app_name">
   <intent-filter>
   <action android:name="android.intent.action.MAIN" />
   <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>

 </application>
</manifest>

The app will start like this..


You can download the complete source code zip file here : TabWidgetBasic

 cheers!!

 I'd love to hear your thoughts!

Monday, November 14, 2011

Splash Screen in Android (Advance)


A splash screen is an image with animation effects that appears while a game or program is loading. It may also be used to describe an introduction of App or page on a website.

So today we will learn how to create a splash screen in Android so that our app will start with Splash screen and then load Home Screen.

in this example i have defined 5 seconds delay to load home screen you may modify as your need.

In the previous example i used thread to manage splash duration here we will use Android's Animation Class
also we will create custom fad animation effects in res/anim folder

so lets try this smart app..


app structure is look like this




-------------------------------------------
App Name: SplashScreenAdvance
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: ActivitySplashScreen
-------------------------------------------

ActivitySplashScreen.java
package com.rdc;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

public class ActivitySplashScreen extends Activity {

	// animation duration you can find in fad_in and fad out xml files
	// in anim folder

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.splash_screen);

		// get the instace of image view
		ImageView image = (ImageView) findViewById(R.id.imageViewSplash);

		// create animation object
		Animation fad = AnimationUtils.loadAnimation(getBaseContext(),
				R.anim.splash_fade_in);

		// create animation listener
		fad.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationEnd(Animation animation) {
				Intent i = new Intent(ActivitySplashScreen.this,
						ActivityHomeScreen.class);
				startActivity(i);
				finish();

				overridePendingTransition(R.anim.splash_fade_in,
						R.anim.splash_fade_out);

			}

			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub
			}

		});

		// start animation
		image.startAnimation(fad);
	}

	// disable home button during splash screen
	@Override
	public void onAttachedToWindow() {
		this.getWindow().setType(
				WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
		super.onAttachedToWindow();
	}

	// disable back button during splash screen
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return false;
	}
}

ActivityHomeScreen.java
package com.rdc;

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

public class ActivityHomeScreen extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_screen);
	}
}
put these two files in res/layout folder
splash_screen.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:layout_height="fill_parent"
		android:layout_width="fill_parent"
		android:src="@drawable/android_splash_image"
		android:id="@+id/imageViewSplash"></ImageView>
</LinearLayout>

home_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:gravity="center">
	<TextView
		android:layout_width="wrap_content"
		android:id="@+id/textView1"
		android:layout_height="wrap_content"
		android:textSize="25sp"
		android:text="@string/homeTitle"></TextView>
</LinearLayout>

create anim folder in res and put below tow files at res/anim splash_fade_in.xml
<alpha
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:interpolator="@android:anim/decelerate_interpolator"
	android:zAdjustment="top"
	android:fromAlpha="0.0"
	android:toAlpha="1.0"
	android:duration="2000" />

splash_fade_out.xml
<alpha
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:interpolator="@android:anim/accelerate_interpolator"
	android:fromAlpha="1.0"
	android:toAlpha="0.0"
	android:duration="3000" />

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
	xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.rdc"
	android:versionCode="1"
	android:versionName="1.0">
	<uses-sdk android:minSdkVersion="10" />

	<application
		android:icon="@drawable/icon"
		android:label="@string/app_name">
		<activity
			android:name=".ActivitySplashScreen"
			android:screenOrientation="nosensor"
			android:configChanges="keyboardHidden|orientation"
			android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"
			android:label="@string/app_name">
			<intent-filter>
			<action android:name="android.intent.action.MAIN" />
			<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
		<activity
			android:name=".ActivityHomeScreen"
			android:label="@string/app_name">
			<intent-filter>
		    <category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>

	</application>
</manifest>

The output Screen will be like this..


You can download the complete source code zip file here : SplashScreenAdvance 

cheers!!

I'd love to hear your thoughts!

Tuesday, November 8, 2011

Splash Screen in Android (Basic)

A splash screen is an image with animation effects that appears while a game or program is loading. It may also be used to describe an introduction of App or page on a website.

So today we will learn how to create a splash screen in Android so that our app will start with Splash screen and then load Home Screen.

in this example i have defined 5 seconds delay to load home screen you may modify as your need.

so lets try this small app..

My Project structure is look like


-------------------------------------------
App Name: SplashScreenBasic
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: ActivitySplashScreen
-------------------------------------------

ActivitySplashScreen.java

package com.rdc;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;

public class ActivitySplashScreen extends Activity {

	// set splash duration 3 seconds
	private final int SPLASH_DISPLAY_LENGTH = 3000;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// hide the notification bar title on screen
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		// make full screen view
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.splash_screen);

		// create a thread for splash
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				Intent i = new Intent(ActivitySplashScreen.this,
						ActivityHomeScreen.class);
				startActivity(i);
				finish();

				overridePendingTransition(R.drawable.splash_fade_in,
						R.drawable.splash_fade_out);

			}
		}, SPLASH_DISPLAY_LENGTH);
	}

	// disable home button during splash screen
	@Override
	public void onAttachedToWindow() {
		this.getWindow().setType(
				WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
		super.onAttachedToWindow();
	}

	// disable back button during splash screen
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return false;
	}

}

ActivityHomeScreen.java
package com.rdc;

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

public class ActivityHomeScreen extends Activity {

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

}


create below two xml files in res/layout folder

splash_screen.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:layout_height="fill_parent"
		android:layout_width="fill_parent"
		android:id="@+id/splash_image"
		android:src="@drawable/splashscreen"></ImageView>
</LinearLayout>

home_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:gravity="center">
	<TextView
		android:layout_width="wrap_content"
		android:id="@+id/textView1"
		android:layout_height="wrap_content"
		android:text="@string/homeTitle"
		android:textSize="25sp"></TextView>
</LinearLayout>

create a drawable folder in resource and put these file for fad animation

splash_fade_in.xml
<alpha
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:interpolator="@android:anim/decelerate_interpolator"
	android:zAdjustment="top"
	android:fromAlpha="0.0"
	android:toAlpha="1.0"
	android:duration="2000" />

splash_fade_out.xml
<alpha
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:interpolator="@android:anim/accelerate_interpolator"
	android:fromAlpha="1.0"
	android:toAlpha="0.0"
	android:duration="3000" />

and you AndroidManifest.xml file will be like this.
<?xml version="1.0" encoding="utf-8"?>
<manifest
	xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.rdc"
	android:versionCode="1"
	android:versionName="1.0">
	<uses-sdk android:minSdkVersion="10" />

	<application
		android:icon="@drawable/icon"
		android:label="@string/app_name">
		<activity
			android:name=".ActivitySplashScreen"
			android:screenOrientation="nosensor"
			android:configChanges="keyboardHidden|orientation"
			android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"
			android:label="@string/app_name">
			<intent-filter>
			<action android:name="android.intent.action.MAIN" />
			<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
		<activity
			android:name=".ActivityHomeScreen"
			android:label="Home Screen">
			<intent-filter>
			<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>

	</application>
</manifest>

The app will start like this..


You can download the complete source code zip file here : SplashScreenBasic

 cheers!!

 I'd love to hear your thoughts!

Saturday, October 22, 2011

Listen SMS-MMS Programmatically Android (Store SMS-MMS Data)

after many hours overtime i got solve this puzzle.. how can we store the incoming (sms/mms) and outgoing (sms/mms) data programmatically?.

MainActivity.java

  
package Com.rdc.listenSmsMms;

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

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.v("In on create", "activty started..");
        
        //start the service to listen 
        startService(new Intent(getBaseContext(),ListenSmsMmsService.class));
    }
}

ListenSmsMmsService.java
  
package Com.rdc.listenSmsMms;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Date;

import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class ListenSmsMmsService extends Service {

 private ContentResolver contentResolver;
 
  
 String substr;
 int k;
 
 @Override
 public IBinder onBind(Intent intent) {  
  return null;
 }
 
 @Override
 public void onCreate() { 
  Log.v("Debug", " service creatd.........");
 }
 
 public void registerObserver() {    
  
  contentResolver = getContentResolver();            
  contentResolver.registerContentObserver(
    Uri.parse("content://mms-sms/conversations/"),
      true, new SMSObserver(new Handler()));          
  Log.v("Debug", " in registerObserver method.........");
 }
 
 //start the service and register observer for lifetime
 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
  Log.v("Debug", "Service has been started..");  
  Toast.makeText(getApplicationContext(),
    "Service has been started.. ", 
    Toast.LENGTH_SHORT).show();  
  registerObserver(); 
  
  return START_STICKY;  
 }
 
 class SMSObserver extends ContentObserver{

  public SMSObserver(Handler handler) {
   super(handler);   
  }
  
  //will be called when database get change
  @Override
  public void onChange(boolean selfChange) {
   super.onChange(selfChange);
   Log.v("Debug", "Observer has been started..");
   
  /*first of all we need to decide message is Text or MMS type.*/
   final String[] projection = new String[]{
     "_id", "ct_t"};
   Uri mainUri = Uri.parse(
     "content://mms-sms/conversations/");
   Cursor mainCursor = contentResolver.
     query(mainUri, projection, 
     null, null, null);
   mainCursor.moveToFirst();
   
   String msgContentType = mainCursor.getString(mainCursor.
     getColumnIndex("ct_t"));
   if ("application/vnd.wap.multipart.related".
     equals(msgContentType)) {
    // it's MMS
          Log.v("Debug", "it's MMS");
          
          //now we need to decide MMS message is sent or received
          Uri mUri = Uri.parse("content://mms");          
          Cursor mCursor = contentResolver.query(mUri, null, null, 
            null, null);
          mCursor.moveToNext();
    int type = mCursor.getInt(mCursor.getColumnIndex("type"));
    
    if(type==1){
     //it's received MMS
     Log.v("Debug", "it's received MMS");
     getReceivedMMSinfo();
    }
    else if(type==2)
    {
     //it's sent MMS
     Log.v("Debug", "it's Sent MMS");
     getSentMMSinfo();
    }    
          
   }
   else{
    // it's SMS
          Log.v("Debug", "it's SMS"); 
          
          //now we need to decide SMS message is sent or received
          Uri mUri = Uri.parse("content://sms");          
          Cursor mCursor = contentResolver.query(mUri, null, null, 
            null, null);
          mCursor.moveToNext();
    int type = mCursor.getInt(mCursor.getColumnIndex("type"));
    
    if(type==1){
     //it's received SMS
     Log.v("Debug", "it's received SMS");
     getReceivedSMSinfo();
    }
    else if(type==2)
    {
     //it's sent SMS
     Log.v("Debug", "it's sent SMS");     
     getSentSMSinfo();
    }
   }//message content type block closed
   
  
  }//on changed closed
  
  
 /*now Methods start to getting details for sent-received SMS*/

  

  //method to get details about received SMS..........
  private void getReceivedSMSinfo() {
   Uri uri = Uri.parse("content://sms/inbox");
   String str = "";
   Cursor cursor = contentResolver.query(uri, null,
     null,null, null);
   cursor.moveToNext();     
   
   // 1 = Received, etc.
   int type = cursor.getInt(cursor.
     getColumnIndex("type"));
   String msg_id= cursor.getString(cursor.
     getColumnIndex("_id"));
   String phone = cursor.getString(cursor.
     getColumnIndex("address"));
   String dateVal = cursor.getString(cursor.
     getColumnIndex("date"));   
   String body = cursor.getString(cursor.
     getColumnIndex("body"));
   Date date = new Date(Long.valueOf(dateVal));
    
      str = "Received SMS: \n phone is: " + phone;
      str +="\n SMS type is: "+type;
   str +="\n SMS time stamp is:"+date;
   str +="\n SMS body is: "+body;
   str +="\n id is : "+msg_id;
    
   
   Log.v("Debug","Received SMS phone is: "+phone);
   Log.v("Debug","SMS type is: "+type);
   Log.v("Debug","SMS time stamp is:"+date);
   Log.v("Debug","SMS body is: "+body);
   Log.v("Debug","SMS id is: "+msg_id);
   
   Toast.makeText(getBaseContext(), str, 
     Toast.LENGTH_SHORT).show();
   Log.v("Debug", "RDC : So we got all informaion " +
     "about SMS Received Message :) ");
   
  }

  //method to get details about Sent SMS...........
  private void getSentSMSinfo() {
   Uri uri = Uri.parse("content://sms/sent");
   String str = "";
   Cursor cursor = contentResolver.query(uri, null, 
     null, null, null);
   cursor.moveToNext();     
   
   // 2 = sent, etc.
   int type = cursor.getInt(cursor.
     getColumnIndex("type"));
   String msg_id= cursor.getString(cursor.
     getColumnIndex("_id"));
   String phone = cursor.getString(cursor.
     getColumnIndex("address"));
   String dateVal = cursor.getString(cursor.
     getColumnIndex("date"));   
   String body = cursor.getString(cursor.
     getColumnIndex("body"));
   Date date = new Date(Long.valueOf(dateVal));
    
      str = "Sent SMS: \n phone is: " + phone;
      str +="\n SMS type is: "+type;
   str +="\n SMS time stamp is:"+date;
   str +="\n SMS body is: "+body;
   str +="\n id is : "+msg_id;
    
   
   Log.v("Debug","sent SMS phone is: "+phone);
   Log.v("Debug","SMS type is: "+type);
   Log.v("Debug","SMS time stamp is:"+date);
   Log.v("Debug","SMS body is: "+body);
   Log.v("Debug","SMS id is: "+msg_id);
   
   Toast.makeText(getBaseContext(), str, 
     Toast.LENGTH_SHORT).show();
   Log.v("Debug", "RDC : So we got all informaion " +
     "about Sent SMS Message :) ");
  }
  
  
  /*now Methods start to getting details for sent-received MMS.*/
  
  // 1. method to get details about Received (inbox)  MMS...
  private void getReceivedMMSinfo() {
   Uri uri = Uri.parse("content://mms/inbox");
   String str = "";
   Cursor cursor = getContentResolver().query(uri, null,null, 
     null, null);
   cursor.moveToNext(); 
   
   String mms_id= cursor.getString(cursor.
     getColumnIndex("_id"));
   String phone = cursor.getString(cursor.
     getColumnIndex("address"));
   String dateVal = cursor.getString(cursor.
     getColumnIndex("date"));
   Date date = new Date(Long.valueOf(dateVal));
   
   // 2 = sent, etc.
   int mtype = cursor.getInt(cursor.
     getColumnIndex("type"));
   String body="";
   
   Bitmap bitmap;
   
   String type = cursor.getString(cursor.
     getColumnIndex("ct"));
   if ("text/plain".equals(type)){
    String data = cursor.getString(cursor.
      getColumnIndex("body"));
    if(data != null){
      body = getReceivedMmsText(mms_id);
    }
    else {
                 body = cursor.getString(cursor.
                   getColumnIndex("text"));
                 //body text is stored here
             }
    }
   else if("image/jpeg".equals(type) ||
     "image/bmp".equals(type) ||
                 "image/gif".equals(type) || 
                 "image/jpg".equals(type) ||
                 "image/png".equals(type)){
     bitmap = getReceivedMmsImage(mms_id);
     //image is stored here
     //now we are storing on SDcard
     storeMmsImageOnSDcard(bitmap);
   }
   
      str = "Sent MMS: \n phone is: " + phone;
      str +="\n MMS type is: "+mtype;
   str +="\n MMS time stamp is:"+date;
   str +="\n MMS body is: "+body;
   str +="\n id is : "+mms_id;
    
   
   Log.v("Debug","sent MMS phone is: "+phone);
   Log.v("Debug","MMS type is: "+mtype);
   Log.v("Debug","MMS time stamp is:"+date);
   Log.v("Debug","MMS body is: "+body);
   Log.v("Debug","MMS id is: "+mms_id);
   
   Toast.makeText(getBaseContext(), str, 
     Toast.LENGTH_SHORT).show();
   Log.v("Debug", "RDC : So we got all informaion " +
     "about Received MMS Message :) ");
  }
  
  
  

  //method to get Text body from Received MMS.........
  private String getReceivedMmsText(String id) {
      Uri partURI = Uri.parse("content://mms/inbox" + id);
      InputStream is = null;
      StringBuilder sb = new StringBuilder();
      try {
          is = getContentResolver().openInputStream(partURI);
          if (is != null) {
              InputStreamReader isr = new InputStreamReader(is,
                "UTF-8");
              BufferedReader reader = new BufferedReader(isr);
              String temp = reader.readLine();
              while (temp != null) {
                  sb.append(temp);
                  temp = reader.readLine();
              }
          }
      } catch (IOException e) {}
      finally {
          if (is != null) {
              try {
                  is.close();
              } catch (IOException e) {}
          }
      }
      return sb.toString();
  }
  
  //method to get image from Received MMS..............
  private Bitmap getReceivedMmsImage(String id) {
   

      Uri partURI = Uri.parse("content://mms/inbox" + id);
      InputStream is = null;
      Bitmap bitmap = null;
      try {
          is = getContentResolver().
            openInputStream(partURI);
          bitmap = BitmapFactory.decodeStream(is);
      } catch (IOException e) {}
      finally {
          if (is != null) {
              try {
                  is.close();
              } catch (IOException e) {}
          }
      }
      return bitmap;
  
  }
  
  //Storing image on SD Card
  private void storeMmsImageOnSDcard(Bitmap bitmap) {
   try {
    
    substr = "A " +k +".PNG";
    String extStorageDirectory = Environment.
      getExternalStorageDirectory().toString();
    File file = new File(extStorageDirectory, substr);
    OutputStream outStream = new FileOutputStream(file);
    bitmap.compress(Bitmap.CompressFormat.PNG, 
      100,outStream);
    outStream.flush();
    outStream.close();

    Toast.makeText(getApplicationContext(), "Image Saved", 
      Toast.LENGTH_LONG).show();
    Log.v("Debug", "Image seved sucessfully");
   }
   catch (FileNotFoundException e) {
    
    e.printStackTrace();
    Toast.makeText(getApplicationContext(), 
      e.toString(),
      Toast.LENGTH_LONG).show();
   } catch (IOException e) {
    
    e.printStackTrace();
    Toast.makeText(getApplicationContext(), 
      e.toString(),
      Toast.LENGTH_LONG).show();
   }
   k++;   
  }
  
  

  /* .......methods to get details about Sent MMS.... */
  private void getSentMMSinfo() {
   

   Uri uri = Uri.parse("content://mms/sent");
   String str = "";
   Cursor cursor = getContentResolver().query(uri, 
     null,null,
     null, null);
   cursor.moveToNext(); 
   
   String mms_id= cursor.getString(cursor.
     getColumnIndex("_id"));
   String phone = cursor.getString(cursor.
     getColumnIndex("address"));
   String dateVal = cursor.getString(cursor.
     getColumnIndex("date"));
   Date date = new Date(Long.valueOf(dateVal));
   // 2 = sent, etc.
   int mtype = cursor.getInt(cursor.
     getColumnIndex("type"));
   String body="";
   
   Bitmap bitmap;
   
   String type = cursor.getString(cursor.
     getColumnIndex("ct"));
   if ("text/plain".equals(type)){
    String data = cursor.getString(cursor.
      getColumnIndex("body"));
    if(data != null){
      body = getSentMmsText(mms_id);
    }
    else {
                 body = cursor.getString(cursor.
                   getColumnIndex("text"));
                 //body text is stored here
             }
    }
   else if("image/jpeg".equals(type) || 
     "image/bmp".equals(type) ||
                 "image/gif".equals(type) || 
                 "image/jpg".equals(type) ||
                 "image/png".equals(type)){
     bitmap = getSentMmsImage(mms_id);
     //image is stored here
     //now we are storing on SDcard
     storeMmsImageOnSDcard(bitmap);
   }
   
      str = "Sent MMS: \n phone is: " + phone;
      str +="\n MMS type is: "+mtype;
   str +="\n MMS time stamp is:"+date;
   str +="\n MMS body is: "+body;
   str +="\n id is : "+mms_id;
    
   
   Log.v("Debug","sent MMS phone is: "+phone);
   Log.v("Debug","MMS type is: "+mtype);
   Log.v("Debug","MMS time stamp is:"+date);
   Log.v("Debug","MMS body is: "+body);
   Log.v("Debug","MMS id is: "+mms_id);
   
   Toast.makeText(getBaseContext(), str, 
     Toast.LENGTH_SHORT).show();
   Log.v("Debug", "RDC : So we got all informaion " +
     "about Sent MMS Message :) ");
  
  }

  
  //method to get Text body from Sent MMS............
  private String getSentMmsText(String id) {   

      Uri partURI = Uri.parse("content://mms/sent" + id);
      InputStream is = null;
      StringBuilder sb = new StringBuilder();
      try {
          is = getContentResolver().openInputStream(partURI);
          if (is != null) {
              InputStreamReader isr = new InputStreamReader(is,
                "UTF-8");
              BufferedReader reader = new BufferedReader(isr);
              String temp = reader.readLine();
              while (temp != null) {
                  sb.append(temp);
                  temp = reader.readLine();
              }
          }
      } catch (IOException e) {}
      finally {
          if (is != null) {
              try {
                  is.close();
              } catch (IOException e) {}
          }
      }
      return sb.toString();
  
  }
  
  //method to get image from sent MMS............
  private Bitmap getSentMmsImage(String id) {
   
      Uri partURI = Uri.parse("content://mms/sent" + id);
      InputStream is = null;
      Bitmap bitmap = null;
      try {
          is = getContentResolver().
            openInputStream(partURI);
          bitmap = BitmapFactory.decodeStream(is);
      } catch (IOException e) {}
      finally {
          if (is != null) {
              try {
                  is.close();
              } catch (IOException e) {}
          }
      }
      return bitmap; 
  
  }
  
 }//smsObserver class closed
}


dont forget to write entries for permissions and service

AndroidManifest.xml
  


    
    
     
 
 
 
 
 
 
  

    
        
            
                
                
            
        
        
          
          
              
              
        
      

    


This code is tested on Emulator for SMS and output will be like this..
For Receiving Text SMS:

For Sending Text SMS:

Thanks!!

any suggestions will be appreciated :)

Saturday, October 8, 2011

Listening incoming sms message in Android

The following code shows "how to get notification when android mobile receive a message"

We will use only Broadcast Receiver's method not any URI query or something else.


So let's create a simple android app, then delete default Activity and create new java class
which extends Broadcast-receiver  look like this

SMSNotification.java
  
package com.rdc;

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


public class SMSNotification extends BroadcastReceiver {
  
  @Override
  public void onReceive(Context context, Intent intent) {  
  
  Toast.makeText(context,"Wow! we got a Message :)",Toast.LENGTH_SHORT).show();
  
 Bundle bundle = intent.getExtras();
 SmsMessage[] msgs = null;
 String str = "";
 if(bundle != null){
  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 +="\n"+"Message is:";
   str += msgs[i].getMessageBody().toString();
   str +="\n";
  }
  
  Log.v("Debug", str);
  Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
 } 
   }
}


AndroidManifest.xml
  


      
   
 
 
 
 
 
  

  
    
      
      
      
      
      
       
    

    


output is like this

cheers!!

I'd love to hear your thoughts!

Wednesday, October 5, 2011

How to call Activity's Method from Service/Adapter or any java class

Some time we need to call the Activity's method from outside the Activity like any Service/Adapter or any java class. So for that i have created this very simple example.

we need to do two steps.
  1. get the instance of Activity in Service.
  2. call Activity class method from Service
so lets try this small app..

-------------------------------------------
App Name: CallActivityMthodFromService
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: MyActivity
-------------------------------------------

 MyActivity.java
package com.rdc;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class MyActivity extends Activity {

	static MyActivity instance;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		instance = this;
		Intent myIntent = new Intent(getBaseContext(), MyService.class);
		startService(myIntent);
	}

	public void showToast() {
		Toast.makeText(getBaseContext(), "called from ervice", 1).show();

	}
}

MyService.java
package com.rdc;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

	@Override
	public IBinder onBind(Intent i) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		Log.v("Debug", "Service has been Created..");
		// code to execute when the service is first created
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.v("Debug", "Service has been Started..");
		Toast.makeText(getBaseContext(), "Service has been Started..",
				Toast.LENGTH_SHORT).show();

		// getting the static instance of activity
		MyActivity activity = MyActivity.instance;

		if (activity != null) {
			// we are calling here activity's method
			activity.showToast();
		}

		return START_STICKY;
	}

}


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">
	<TextView
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:text="@string/hello" />
</LinearLayout>


and Manifest file will be
<?xml version="1.0" encoding="utf-8"?>
<manifest
	xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.rdc"
	android:versionCode="1"
	android:versionName="1.0">
	<uses-sdk android:minSdkVersion="10" />

	<application
		android:icon="@drawable/icon"
		android:label="@string/app_name">
		<activity
			android:name=".MyActivity"
			android:label="@string/app_name">
			<intent-filter>
			<action android:name="android.intent.action.MAIN" />
			<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
		<service
			android:enabled="true"
			android:name=".MyService" />

	</application>
</manifest>


The output Screen will be like this..


You can download the complete source code zip file here : CallActivityMthodFromService 

 cheers!!

 I'd love to hear your thoughts!

Friday, September 30, 2011

Grid View Demo With Images

GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.

We are going to create a Grid View to show Images, where we can select each item via click.

so lets create simple app with default activity "GridViewActivity" and put this code inside it.
  
package com.rdc;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class GridViewActivity extends Activity {
    
 GridView gridView;
 
 static final String[] MOBILE_OS = new String[]{
  "Android", "iOS", "Windows", "Balckberry",
 };
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        gridView = (GridView) findViewById(R.id.gridView1);
        
        gridView.setAdapter(new ImageAdapter(this, MOBILE_OS));
        
        gridView.setOnItemClickListener(new OnItemClickListener(){
         public void onItemClick(AdapterView parent, View v, 
           int position, long id){
          Toast.makeText(getApplicationContext(),
          ((TextView) v.findViewById(R.id.grid_item_label))
          .getText(), Toast.LENGTH_SHORT).show();
         }
        });
    }
}

ImageAdapter.java
  
package com.rdc;


import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ImageAdapter extends BaseAdapter{
 
 
 private Context context;
 private final String[] mobileValues;
 
 public ImageAdapter(Context context, String[] 
   mobileValues){
  this.context=context;
  this.mobileValues=mobileValues;
 }
 
 public View getView(int position, View convertView, 
   ViewGroup parent){
  LayoutInflater inflater = (LayoutInflater) context
    .getSystemService(Context.
      LAYOUT_INFLATER_SERVICE);
  
  View gridView;
  if(convertView == null){
   gridView = new View(context);
   gridView = inflater.inflate(
     R.layout.mobile, null);
   
   TextView textView = (TextView) gridView.
     findViewById(R.id.grid_item_label);
   textView.setText(mobileValues[position]);
   
   ImageView imageView = (ImageView) gridView.
     findViewById(
       R.id.grid_item_image);
   String mobile = mobileValues[position];
  
   if(mobile.equals("Android")){
    imageView.setImageResource(
      R.drawable.android_logo);
   }
   else if(mobile.equals("iOS")){
    imageView.setImageResource(
      R.drawable.ios_logo);
   }
   else if(mobile.equals("Windows")){
    imageView.setImageResource(
      R.drawable.windows_logo);    
   }   
   else if(mobile.equals("BlackBerry")){
    imageView.setImageResource(
      R.drawable.ios_logo);
   }   
  }
  else{
   gridView = (View) convertView;
  }
  return gridView;
 }

 @Override
 public int getCount() {
  // TODO Auto-generated method stub
  return mobileValues.length;
 }

 @Override
 public Object getItem(int position) {
  // TODO Auto-generated method stub
  return null;
 }

 @Override
 public long getItemId(int position) {
  // TODO Auto-generated method stub
  return 0;
 }
}

main.xml
  


 

mobile.xml
  


  
  
  
  
  
     
    


you need to put these icons in res/drawable-mdpi folder or any:

Then our output is:

Sunday, September 18, 2011

How to add images in Android Emulator

how to add images to gallery in android emulator??

want to put some pics in emulator to start playing with animation stuff or media??

very easy !!

If you are developing on Eclipse IDE..Look at top-right corner "DDMS" tab. yes press it and go to this directory path.

/mnt/sdcard/DCIM/100ANDRO folder
now push image file using  "push a file on to the device" icon
like this..

okay now come to Android Emulator and click on "Dev Tools" --> "Media Scanner" to  synchronize

yes!! done.. now you should go to library you will get like this.

Life is so simple if we can share our knowledge to other isn't it.... :D

 I'd love to here your thoughts!!

Thursday, September 15, 2011

GridView Demo with Text

GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.

We are going to create a Grid View to show Text, where we can select each item via click.

so lets create simple app with default activity "GridViewActivity" and put this code inside it.
  
package com.rdc;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class GridViewActivity extends Activity {
 
 GridView gridView;

 static final String[] numbers = new String[]{
  "A", "B", "C", "D",
  "E", "F", "G", "H",
 };
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        gridView = (GridView) findViewById(R.id.gridView1);
        
        ArrayAdapter<String> adapter = new ArrayAdapter<String>
        (this,android.R.layout.simple_list_item_1, numbers);
        
        gridView.setAdapter(adapter);
        
        gridView.setOnItemClickListener(new OnItemClickListener()
        {
         public void onItemClick(AdapterView parent, 
           View v,int position, long id){
          
          Toast.makeText(getApplicationContext(),
           "Selected: " +((TextView) v).getText(), 
           Toast.LENGTH_SHORT).show();
         }
        });        
   }
}

and the main.xml file is
  


 


out put is like this

Tuesday, September 13, 2011

Create Transparent Activity

Today we are goning to learn "How to create Transparent Activity ?"
we need to create two activities and a transparent style theme to acheive this.

let's start with creating simple app with default activity "first" and change
main.xml to first.xml in res/layout folder.

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

public class FirstActivity extends Activity 
                implements OnClickListener {
   private Button btnLoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first);
        
        
        btnLoad=(Button) findViewById(R.id.btnload);
        btnLoad.setOnClickListener(this);
    }
 @Override
 public void onClick(View v) {
  Intent i = new Intent(this,SecondActivity.class);
        startActivity(i);
  
 }
}

first.xml
  


    

    




then same way create second activity with second.xml file like this
  
package com.rdc;

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

public class SecondActivity extends Activity {
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);        
    }
}

and the second.xml is
  


  
    
    


now create "styles.xml" in res/values folder
  


  


and also create and color.xml file in res/values
  

  #75AADB
  #00000000


at last make entries for activities and style theme in manifest file
  


    

    
        
            
                
                
            
        
        
        
     
        

    


now if you done all the stuff in right way you will get output like this: (after tapping the button to load transparent activity)

cheers!!

I'd love to hear your thoughts! 

Thursday, August 18, 2011

ListView in Android (Advance)

We have already know how to show the list in Android see tutorial ListView in Android (Basic)


This tutorial describes how to use ListView and ListActivity in Android.
While we will create array list in a separate XML file.
also it will show the new page when you click on List Item.

Project Structure is look like this


okay! so let's try this small app 


 -------------------------------------------
App Name: ListViewBasic
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default ListActivity Name: ActivityListView
------------------------------------------- 

ActivityListView.java


package com.rdc;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ActivityGamesList extends Activity {

 private String[] gamelistArray;
 private String[] gameDetailsListArray;
 private ListView listGames = null;
 ArrayAdapter<String> adapter;

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

  listGames = (ListView) findViewById(R.id.listViewGame);
  gamelistArray = getResources().getStringArray(R.array.gameslist);
  gameDetailsListArray = getResources().getStringArray(
    R.array.gamesDetails);

  adapter = new ArrayAdapter<String>(this,
    android.R.layout.simple_list_item_1, android.R.id.text1,
    gamelistArray);

  listGames.setAdapter(adapter);

  listGames.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {

    // Get the item that was clicked
    Object itemName = listGames.getItemAtPosition(position);
    String keyword = itemName.toString();
    String info = gameDetailsListArray[position];
    Toast.makeText(getApplicationContext(),
    "You have selected:  " + keyword, Toast.LENGTH_SHORT)
      .show();
    Intent i = new Intent(getBaseContext(),
      ActivityGameDetails.class);
    i.putExtra("info", info);
    i.putExtra("name", keyword);
    startActivity(i);

   }
  });
 }
}


ActivityGameDetails.java
package com.rdc;

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

public class ActivityGameDetails extends Activity {

 private TextView txtTitle = null;
 private TextView txtDetails = null;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.game_details);
  Bundle bundle = new Bundle();
  String info = getIntent().getStringExtra("info");
  txtTitle = (TextView) findViewById(R.id.textView1);
  txtTitle.setText(info);
  String name = getIntent().getStringExtra("name");
  txtDetails = (TextView) findViewById(R.id.txtgamedetailsTitle);
  txtDetails.setText("Details of " + name);
 }
}


create these xml files in res/layout folder 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="match_parent"
 android:layout_height="match_parent">
 <ListView
  android:layout_height="wrap_content"
  android:layout_width="match_parent"
  android:id="@+id/listViewGame"></ListView>

</LinearLayout>

game_details.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:weightSum="1">
 <TextView
  android:text="TextView"
  android:layout_height="wrap_content"
  android:layout_width="match_parent"
  android:layout_weight="0.30"
  android:gravity="center"
  android:textSize="20sp"
  android:id="@+id/txtgamedetailsTitle"></TextView>
 <ScrollView
  android:id="@+id/layscroll"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_weight="0.70">
  <TextView
   android:id="@+id/textView1"
   android:text="@string/gameDetails"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"></TextView>
 </ScrollView>

</LinearLayout>


create these below xml files in res/values folder arraylist_games.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
       <string-array name="gameslist">
        <item>Soccer</item>
        <item>Cricket</item>
        <item>Chess</item>
        <item>WWE</item>
        <item>NFS Most Wanted</item>
        <item>Counter Strike</item>
        <item>Angry Birds</item>
        <item>Lord of the Rings</item>
        <item>Mario</item>
        <item>Prince of Persia</item>
        <item>Resident Evil</item>
        <item>Far Cry</item>
        <item>Minesweeper</item>
        <item>Jumper</item>      
        
    </string-array>
       
    
    <string-array name="gamesDetails">
        <item>Association football, more commonly known as football or soccer, is a sport played between two teams of eleven players with a spherical ball. At the turn of the 21st century, the game was played by over 250 million players in over 200 countries, making it the world\'s most popular sport..</item>
        <item>Cricket is a bat-and-ball game played between two teams of 11 players on a field, at the centre of which is a rectangular 22-yard long pitch</item>
        <item>Chess is a two-player board game played on a chessboard, a square checkered board with 64 squares arranged in an eight-by-eight grid.</item>
        <item> WWE is an American publicly traded, privately controlled entertainment company dealing primarily in professional wrestling which despite being scripted and not real are very popular, with major revenue sources also coming from film, music, product licensing, and direct product sales.</item>
        <item>Need for Speed: Most Wanted is an upcoming 2012 racing video game, developed by British games developer Criterion Games and published by Electronic Arts. Announced on 4 June 2012, during EA\'s E3 press conference, Most Wanted is the nineteenth title in the long-running Need for Speed series and second game in the Most Wanted series.</item>
        <item>The game was the most played Half-Life modification in terms of players, according to GameSpy in 2008.</item>
        <item>Angry Birds is a strategy puzzle video game developed by Finnish computer game developer Rovio Mobile. Inspired primarily by a sketch of stylized wingless birds, the game was first released for Apple\'s iOS in December 2009.</item>
        <item>The Lord of the Rings is an epic film trilogy consisting of three fantasy adventure films, directed by Peter Jackson, based on the three-volume book of the same name by English author J. R. R. Tolkien.</item>
        <item>Mario is a fictional character in the Mario video game franchise by Nintendo, created by Japanese video game designer Shigeru Miyamoto. Serving as Nintendo\'s mascot and the eponymous protagonist of the series, Mario has appeared in over 200 video games since his creation.</item>
        <item>Prince of Persia is a video game franchise created by Jordan Mechner, originally developed for and released on the Apple II Computer in 1989. The original game and its first sequel were 2D platform games, but the series made the switch to three-dimensional following the release of Prince of Persia 3D in 1999.</item>
        <item>Resident Evil, originally released as Bio Hazardin Japan, is a survival horror video game by Capcom. The first installment in the Resident Evil series was originally released in 1996 for the PlayStation and was soon ported to the Sega Saturn and PC, as well as the Nintendo DS some years later.</item>
        <item>Far Cry is first-person shooter video game developed by Crytek Studios and published by Ubisoft on March 23, 2004, for Microsoft Windows. Far Cry sold 730,000 units within four months of release.It received positive reviews upon release. The original game has since spawned a series of sequels and spin-off games and a movie.</item>
        <item>Minesweeper is a single-player video game. The object of the game is to clear an abstract minefield without detonating a mine. </item>
        <item>City Jumper : You can leap over buildings in a single bound, but scrape your back on the Golden Gate bridge and you will be cut in half.</item>
        
    </string-array>    
</resources>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="10" />

 <application
  android:icon="@drawable/icon"
  android:label="@string/app_name">
  <activity
   android:name=".ActivityGamesList"
   android:label="Games List">
   <intent-filter>
   <action android:name="android.intent.action.MAIN" />
   <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>

  <activity
   android:name=".ActivityGameDetails"
   android:label="Game Details">
   <intent-filter>
   <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>

 </application>
</manifest>

The output Screen will be like this..
                                   
                                                                Games Name List

When you select any one it will show the Game Details like this..



You can download the complete source code zip file here : ListViewAdvance

 cheers!!

 I'd love to hear your thoughts!