Sunday, August 12, 2012

How to Pick Image from Gallery in Android



Today I just learn and going to share with you,
how we can get an image From Gallery in our Android app
so below is the step by step description also at last
you can find zip source code of this example.

We will create very simple app to do this work
 -------------------------------------------
App Name: PickGalleryImage
Package Name: com.rdc.activity
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: PickGalleryImageActivity.java
-------------------------------------------

PickGalleryImageActivity.java

package com.rdc.activity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class PickGalleryImageActivity extends Activity implements
		OnClickListener {

	private static int RESULT_LOAD_IMAGE = 1;
	private Button btnLoadImage = null;
	private ImageView imageView = null;

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

		btnLoadImage = (Button) findViewById(R.id.button_LoadPicture);
		btnLoadImage.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {

		Intent i = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore
                              .Images.Media.EXTERNAL_CONTENT_URI);

		startActivityForResult(i, RESULT_LOAD_IMAGE);

	}
	
	
	@Override
    protected void onActivityResult(int requestCode, 
                                     int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	
		if (requestCode == RESULT_LOAD_IMAGE && 
                              resultCode == RESULT_OK && null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();
			
			imageView = (ImageView) findViewById(R.id.imageView);
			imageView.setImageBitmap(BitmapFactory
                            .decodeFile(picturePath));
		
		}
    
    
    }
	
}
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:layout_width="fill_parent"
		android:layout_weight="1"
		android:layout_height="wrap_content"
		android:id="@+id/imageView"></ImageView>
	<Button
		android:layout_height="wrap_content"
		android:text="Load Picture"
		android:layout_width="wrap_content"
		android:layout_weight="0"
		android:layout_gravity="center"
		android:id="@+id/button_LoadPicture"></Button>
</LinearLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
	xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.rdc.activity"
	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=".PickGalleryImageActivity"
			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 output Screen will be like this..

Note: before click on upload image button make sure your Android Device is not connected with Computer.

Click to upload image


Just select any one image and see you got it here


You can download the complete source code zip file here : PickGalleryimage.zip

Tuesday, July 31, 2012

Google Map Tutorial Android (Advance)


Hello Android Guys...hope you doing great!!

We know already how to get Google map in our Android App see my earlier tutorial post
Google Map Tutorial Android (Basic)

Note: Because we need to Get Google map API key to Get map in our app
 I have wrote step by step simple tutorial see and put in you main.xml file see below


Okay so today we are going to add some more new things to our Google Maps

1. Enter location name and Go to particular location
2. Bookmark location (POI) place of interest on map
3. Get the location name/coordinates where you touched on map
4. Zoom-in and Zoom-out map location

Let's start coding stuff..create an Android app with



 -------------------------------------------
App Name: GoogleMapAdvance
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 /  Google API 10
Default MapActivity Name: ActivityGoogleMap
-------------------------------------------

ActivityGoogleMap

package com.rdc.gmap;

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

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class ActivityGoogleMap extends MapActivity 
implements OnClickListener {
 private MapView mapView = null;
 private Button btnGo = null;
 private EditText editLocation = null;
 private MapController mController = null;
 private GeoPoint gPoint = null;

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

  // to add zoom in and zoom out default buttons
  mapView = (MapView) findViewById(R.id.mapView);
  mapView.setBuiltInZoomControls(true);

  btnGo = (Button) findViewById(R.id.buttonGo);
  btnGo.setOnClickListener(this);

  editLocation = (EditText) findViewById(R.id.editText1);

  // load bangalore as default location
  browseLocation();

  // ---Add a location marker---
  MapOverlay mapOverlay = new MapOverlay();
  List<Overlay> listOfOverlays = mapView.getOverlays();
  listOfOverlays.clear();
  listOfOverlays.add(mapOverlay);

  mapView.invalidate();
 }

 @Override
 public void onClick(View v) {
  if (btnGo == v) {
   String location = editLocation.getText().toString();
   if (location.equalsIgnoreCase("")) {
   Toast.makeText(getBaseContext(),"Please Enter location!!",
      Toast.LENGTH_SHORT).show();
   } else {

    String map_location = "geo:0,0?q=" + location;
    Uri geoUri = Uri.parse(map_location);
    Intent mapCall = new Intent(Intent.ACTION_VIEW, geoUri);
    startActivity(mapCall);

    // clear old location string
    location = null;
   }

  }

 }

 @Override
 protected boolean isRouteDisplayed() {
  // TODO Auto-generated method stub
  return false;
 }

 // to load particular location on g-map
 public void browseLocation() {
  mController = mapView.getController();
  String coordinates[] = { "12.917233", "77.620811" };
  double lat = Double.parseDouble(coordinates[0]);
  double lng = Double.parseDouble(coordinates[1]);

  gPoint = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));

  mController.animateTo(gPoint);
  mController.setZoom(17);
 }

 // create inner class to add marker at any place on g-map
 class MapOverlay extends com.google.android.maps.Overlay {

  // add bookmark on map
  @Override
  public boolean draw(Canvas canvas, MapView mapView, 
    boolean shadow, long when) {
   super.draw(canvas, mapView, shadow);

   // ---translate the GeoPoint to screen pixels---
   Point screenPts = new Point();
   mapView.getProjection().toPixels(gPoint, screenPts);

   // ---add the marker---
   Bitmap bmp = BitmapFactory.decodeResource(getResources(),
     R.drawable.red_pushpin2);
   canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 50, null);
   return true;
  }

  // get the location where you touched on map
  @Override
  public boolean onTouchEvent(MotionEvent event, MapView mapView) {
   // ---when user lifts his finger---
   if (event.getAction() == 1) {
    GeoPoint p = mapView.getProjection().fromPixels(
      (int) event.getX(), (int) event.getY());

    Geocoder geoCoder = new Geocoder(getBaseContext(),
      Locale.getDefault());
    try {
     List<Address> addresses = geoCoder.getFromLocation(
      p.getLatitudeE6()/ 1E6, p.getLongitudeE6()/ 1E6,
        1);

     String add = "";
     if (addresses.size() > 0) {
      for (int i = 0; i < addresses.get(0)
        .getMaxAddressLineIndex(); i++)
      add += addresses.get(0).getAddressLine(i) + "\n";
     }

     Toast.makeText(getBaseContext(), add, 
      Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
     e.printStackTrace();
    }
    return true;
   } else
    return false;
  }

 }

}
main.xml

Note: make sure you must have Google Map API key to put in Map View in main.xml file
(This is the mistake often made by newbie)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:weightSum="1"
 android:layout_height="fill_parent"
 android:layout_width="fill_parent">
 <LinearLayout
  android:gravity="center"
  android:layout_height="wrap_content"
  android:layout_width="match_parent"
  android:id="@+id/linearLayout1"
  android:layout_weight="0.02"
  android:weightSum="1">
  <Button
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_marginLeft="2dp"
   android:layout_weight=".10"
   android:id="@+id/buttonGo"
   android:text=" Go "></Button>
  <EditText
   android:layout_height="wrap_content"
   android:id="@+id/editText1"
   android:lines="1"
   android:singleLine="true"
   android:layout_width="wrap_content"
   android:layout_marginRight="2dp"
   android:layout_weight=".90"></EditText>
 </LinearLayout>
 <LinearLayout
  android:id="@+id/laymap"
  android:layout_width="fill_parent"
  android:orientation="vertical"
  android:layout_height="wrap_content"
  android:layout_weight="0.98">
  <com.google.android.maps.MapView
   android:id="@+id/mapView"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:enabled="true"
   android:clickable="true"
   
   android:apiKey="0iuCzAK4N1AoTya_fr62sB7NXXPqkWqF-OCNMEg" />
 </LinearLayout>
<!-- you need to replace your Google map API key here see apiKey="" -->
</LinearLayout>


and Manifest file is

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

 <uses-permission android:name="android.permission.INTERNET" />
 <application
  android:icon="@drawable/icon"
  android:label="@string/app_name">

  <uses-library android:name="com.google.android.maps" />
  <activity
   android:name=".ActivityGoogleMap"
   android:theme="@android:style/Theme.NoTitleBar"
   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>


Default Output screen will load as Bangalore and Mark it



 if you touch any place on map it shows details like this

 when you enter any location and click Go...it loads new location...




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

 cheers!!

 I'd love to hear your thoughts!

Monday, July 30, 2012

Google Map Tutorial Android (Basic)


In this tutorial we will learn how can we add google map into our android app in a very easy & simple way.

Note:  Because the Maps library is not a part of the standard Android library, you must  remember four things at-least to get G-Map in our app .

1. Obtaining a Google Maps Android API Key to get G-Map view in our app.
2.Select Android SDK with Google APIs (when create new app)
3. We need to extends MapActivity
4. Your emulator also created with Google API SDK to run Google map apps (before run app).

so let's try this small app

First is first: Obtain Google Maps Android API
***************************************************************************
1. Create a folder in C drive called "C:\Android"

2. Go to this path "C:\Program Files\Java\<JDK_version_number>\bin"
or where you installed java, copy "keytool.exe" file and put in our created folder " Android ".

3. Now we need to look for "debug.keystore" for probably you can find here

  •     Windows Vista: C:\Users\\.android\debug.keystore
  •     Windows XP: C:\Documents and Settings\\.android\debug.keystore
  •     OS X and Linux: ~/.android/debug.keystore 

In my system i got here "C:\Users\RDC\.android\debug.keystore"

Now copy this file and put into our folder " Android "

4. open command prompt and go to bin folder in prompt.
 then hit command
--------------------------------------------------------------------------------------------------------
keytool.exe -list -alias androiddebugkey -keystore "C:\android\debug.keystore" -storepass android -keypass android
--------------------------------------------------------------------------------------------------------
Now we need to copy MD5 key so right click on command prompt and "mark" then copy and save in Text file. see below image...



Copy MD5 key and open this developer-page and sign in.
then paste here MD5 fingerprint and Generate API key this way


after generating key the result screen will be


you can use this key whenever wants to develop Google map app in this development environment only.

Okay Great!! now we are ready to go...make sure don't use mine key its valid only for my development environment so use your own key :D

*****************************************************************************


Let's create new android app this way..

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

ActivityGoogleMap.java
package com.rdc.gmap;

import android.os.Bundle;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;

public class ActivityGoogleMap extends MapActivity {
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //to add zoom in and zoom out default buttons
        MapView mapView = (MapView) findViewById(R.id.mapView);
        mapView.setBuiltInZoomControls(true);
    }
    
    @Override
 protected boolean isRouteDisplayed() {
  // TODO Auto-generated method stub
  return false;
 }
}

look important Google API key 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">
 <com.google.android.maps.MapView
  android:id="@+id/mapView"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:enabled="true"
  android:clickable="true"
  android:apiKey="0iuCzAK4N1AoTya_fr62sB7NXXPqkWqF-OCNMEg" />

</LinearLayout>


and Manifest file must be like
<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc.gmap"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="10" />
 <uses-permission android:name="android.permission.INTERNET" />
 <application
  android:icon="@drawable/icon"
  android:label="@string/app_name">

  <uses-library android:name="com.google.android.maps" />
  <activity
   android:name=".ActivityGoogleMap"
   android:theme="@android:style/Theme.NoTitleBar"
   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>

Now create Emulator using Google API SDK see below image

The output Screen will be like this..


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

 cheers!!

 I'd love to hear your thoughts!

Wednesday, July 4, 2012

Android Tricks

How to Disable Home Button
    @Override
    public void onAttachedToWindow()
    {  
        this.getWindow().setType(WindowManager.
          LayoutParams.TYPE_KEYGUARD_DIALOG);     
        super.onAttachedToWindow();  
    }

How to Disable Back Button
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return false;
    }

How to Disable Soft Keypad
final EditText txtName = (EditText) findViewById(R.id.txtName);
txtName.setInputType(InputType.TYPE_NULL);

How to Make Static Rotation/orientation in Android
        //if you want to lock screen for always Portrait mode
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                                     or
        //if you want to lock screen for always Landscape mode
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);



How to Disable screen Rotation/orientation in Android (better way is java code)
        
//put this code in Manifest file, activity tag
android:screenOrientation="nosensor"
android:configChanges="keyboardHidden|orientation|screenSize"
/* or even you can do it by programmatically -- just put 
Configuration code in onResume method before calling super 
like this */
@Override
protected void onResume() {
    int currentOrientation = getResources().getConfiguration()
                               .orientation;
    if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) 
    {
        setRequestedOrientation(ActivityInfo
                    .SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
    }
    else {
        setRequestedOrientation(ActivityInfo
                    .SCREEN_ORIENTATION_SENSOR_PORTRAIT);
    }
    super.onResume();
}
How to Disable Title Bar and Make Full Screen View
        
//1. put this line to manifest file in Application tag
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"

//2. put below code in your activity onCreate method

//to disable notification bar (Top Bar)
        requestWindowFeature(Window.FEATURE_NO_TITLE);        
                         
        
        //to set full screen view
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                     WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        //make sure code should be before calling below method
        setContentView(R.layout.main);

How to Create Alert Dialog Box in Android
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("App has been started..")
               .setCancelable(false)
               .setTitle("Alert Box")           
               .setNegativeButton("OK", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                   }
               });
        AlertDialog alert = builder.create();
        alert.show();


How to Create Toast message in Android
        Toast.makeText(getApplicationContext(), "I am splash message..", 
          Toast.LENGTH_LONG).show();

How to create Progress Dialog in Android
        ProgressDialog dialog = ProgressDialog.show(this, "", 
                "Loading. Please wait...", true);

Load Home Screen Programmatically in Android
  //to load home screen put this code in onClick method of desired button
  Intent startMain = new Intent(Intent.ACTION_MAIN);
  startMain.addCategory(Intent.CATEGORY_HOME);
  startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(startMain)

Start/Load Activity from Activity
//put this code where you want to load another Activity
Intent intent = new Intent(FirstActivty.this, SecondActivity.class);

//below 2 lines (Flags) are optional
// 1. if set, it will clear the back stack
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

// 2. If set, this activity will become the start of a new task
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(intent);

Make a Phone Call
String mobileNo = "+919741817902";
String uri = "tel:" + mobileNo.trim() ;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
startActivity(intent);

//add permission to Manifest file

How to check WiFi is Connected or Not
public void chekcWifiConnectDisconnect() {
  ConnectivityManager connManager = (ConnectivityManager) 
    getSystemService(CONNECTIVITY_SERVICE);
  NetworkInfo mWifi = connManager
    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

  if (mWifi.isConnected()) {
   Log.v("Debug", "Wifi is connectd..");   
  } else {
   Log.v("Debug", "Wifi is not connectd..");   
  }

}

//dont forget to put Wifi permission in manifest file

Monday, July 2, 2012

Read & Store Log-cat Programmatically in Android

Android provide Logcat option with ADB to Debugg the Application.

So we can test app on Emulator and with the help of Logcat we can easily trace the Error details.

But if We are testing on Real Android Device and that is not connected with system then its hard know where we are getting exception, error etc.

so for that i wrote this Tutorial

We can read the Logcat details programmatically and also at run-time we can store in Text file and later we can see the error details.

so what we will do in this code:

  • Read the logcat
  • Showing the logcat on TextView
  • Create a Text file
  • store logcat into Text file
  • and finally save file into SDCard.

see below code snap..

//to read the logcat programmatically
try {
 Process process = Runtime.getRuntime().exec("logcat -d");
 BufferedReader bufferedReader = new BufferedReader(
 new InputStreamReader(process.getInputStream()));

        StringBuilder log=new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) 
       {
         log.append(line);
       }      
} 
catch (IOException e) {
}

//to create a Text file name "logcat.txt" in SDCard
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/myLogcat");
dir.mkdirs();
File file = new File(dir, "logcat.txt");


don't forget to add permission for read log-cat in manifest file



add permission for writing text file to SDCard file



So lets create a small App to do this things

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

LogTest.java
package com.rdc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

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

public class LogTest extends Activity {
 
 private StringBuilder log;
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);
   try {
    Process process = Runtime.getRuntime().exec("logcat -d");
    BufferedReader bufferedReader = new BufferedReader(
    new InputStreamReader(process.getInputStream()));
 
    log=new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
      log.append(line);
    }
    TextView tv = (TextView)findViewById(R.id.textView1);
    tv.setText(log.toString());
  } catch (IOException e) {
  }       

 
 //convert log to string
 final String logString = new String(log.toString());
 
 //create text file in SDCard
 File sdCard = Environment.getExternalStorageDirectory();
 File dir = new File (sdCard.getAbsolutePath() + "/myLogcat");
 dir.mkdirs();
 File file = new File(dir, "logcat.txt");

 try {  
  //to write logcat in text file
  FileOutputStream fOut = new FileOutputStream(file);
  OutputStreamWriter osw = new OutputStreamWriter(fOut); 

        // Write the string to the file
        osw.write(logString);            
        osw.flush();
        osw.close();
 } catch (FileNotFoundException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 }
  }
}

main.xml

 
 
 


and the manifest file: make sure you need to add permission

    
    
    
 

    
        
            
                
                
            
        

    


you can check the stored file open DDMS in eclipse and go to this path (in my cash)

File Explorer

data/mnt/sdcard/myLogcat/logcat.txt

now you can pull out this "logfile.txt" and store in local system. see below snap shot


also if you execute this app it will show you the log-cat on TextView with Scrolling like this

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


cheers!!

I'd love to hear your thoughts!

Thursday, June 28, 2012

Disable Title Bar or Full Screen View in Android

Today i learn how to disable Notification bar (Battery, Network Status info Bar ) Top of the Screen.

and how can we set Full Screen View to Our Application Screen.

Just a pretty simple code see below..

//to disable notification bar (Top Bar)
  requestWindowFeature(Window.FEATURE_NO_TITLE);
     
 //to set full screen view
  getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                       WindowManager.LayoutParams.FLAG_FULLSCREEN);

Note: Above code put before loading the main view or we can say before this line
setContentView(R.layout.main);

also i made simple app to achieve this if need then have look on it.

-------------------------------------------
App Name: DisableTitleBar
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: MyActivity
-------------------------------------------
so here is the code 

MyActivity.java

package com.rdc;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class MyActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
        
     //to disable notification bar (Top Bar)
     requestWindowFeature(Window.FEATURE_NO_TITLE);
        
     //to set full screen view
     getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
     //make sure code should be before calling below method
     setContentView(R.layout.main);
  }
}

main.xml

 
 
  
 



AndroidManifest.xml




 
  
  
  
  
 




The output will be like this..



I'd love to hear your thoughts!

Friday, June 15, 2012

Disable Soft KeyPad in Android

Today we will learn another small trick to disable the softkeypad in Android

Sometime you need to disable the Soft Keypad / Virtual Keypad and want to input from either Physical Keypad or Design your own keypad.

Pretty simple and only single line code i have written below

        //disable soft keypad
        txtName.setInputType(InputType.TYPE_NULL);


also i made simple app to achieve this if need then have look on it.

-------------------------------------------
App Name: DisableKeypad
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: DisableKeypadActivity
-------------------------------------------
so here is the code

DisableKeypadActivity.java

package com.rdc;

import android.app.Activity;
import android.os.Bundle;
import android.text.InputType;
import android.widget.EditText;

public class DisableKeypadActivity extends Activity {
    private EditText txtName=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);     
        setContentView(R.layout.main);
        
        //get the id of edit text 
        txtName =(EditText) findViewById(R.id.txtName);
        
        //disable soft keypad
        txtName.setInputType(InputType.TYPE_NULL);
    }
}

main.xml

 
 
  
 



AndroidManifest.xml




 
  
  
  
  
 




Tested on Real Androd Device [Sony Ericsson (XPERIA)] the output will be like this..


I'd love to hear your thoughts!

Sunday, June 10, 2012

How to add Google ads in Android apps (Google Admob Ads)

These day you can find many Android app are having great features you know what still they are FREE available in Android Market/Google Play why?

Because many of those earning money through Google Ad-mob Ads showing in the apps.

so the question is how we can integrated these Google or Any ads into our Android Apps.

I am going to write this page to achieve this....

Before starting codding stuff we need  Google Advertisement Publisher ID.

Get Ads Publisher ID

First of all you need to sign-up account at Google AdSense
if you don't have then fill-up some bank and transaction stuff you will get you client ID

eg. Mine is "a1500db2724b9b8"

okay now let's create a small app with...
 -------------------------------------------
App Name: GoogleAdMob
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 /  API 10
Default Activity Name: ActivityGoogleAdMob
-------------------------------------------


Download and Add Google AdMob SDK

You can download latest Google AdMob Ads SDK here
now we need to add this sdk into our GoogleAdMob app

So right click on project --> properties-->
java build path -->Libraries-->Add External JARs see below image




Now start some coding stuff this way... your main activity should be..

ActivityGoogleAdMob.java

package com.rdc;

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

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class ActivityGoogleAdMob extends Activity {
	private AdView adView = null;
	private static final String ADMOB_ID = "a1500db2724b9b8";

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

		// Create the adView
		adView = new AdView(this, AdSize.BANNER, ADMOB_ID);

		// Lookup your LinearLayout assuming it’s been given
		// the attribute android:id="@+id/mainLayout"
		LinearLayout lay = (LinearLayout) findViewById(R.id.mainLayout);

		// Add the adView to it
		lay.addView(adView);

		// Initiate a generic request to load it with an ad
		adView.loadAd(new AdRequest());
	}

	@Override
	public void onDestroy() {
		if (adView != null) {
			adView.destroy();
		}
		super.onDestroy();
	}

}

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


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

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

	<application
		android:icon="@drawable/icon"
		android:label="@string/app_name">
		<activity
			android:name=".ActivityGoogleAdMob"
			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="com.google.ads.AdActivity"
			android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
	</application>
</manifest>

Note: you must have app target is API 13 or newer
see the file "default.properties"
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your
# project structure.

# Project target.
target=android-13

The output Screen will be like this..



You can download the Google AdMobSDK 6.0 and complete source code zip file here : GoogleAdMob

cheers!!

 I'd love to hear your thoughts!

Saturday, June 2, 2012

Disable Android Screen Rotation/Orientation

Some time you need to Disable or Lock the screen orientation.

just need to add this code in your activity which you want to lock


//for Portrait Mode only
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                                                           or
//for Landscape Mode only
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

well its pretty simple to achieve this, still i have created a small app
-------------------------------------------
App Name: DisableScreenOrientation
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: MyActivity
-------------------------------------------
so here is the code

MyActivity.java

package com.rdc;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;

public class MyActivity extends Activity {
   
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
        
      //if you want to lock screen for always Portrait mode
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
      //if you want to lock screen for always Landscape mode
      //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    }
}

main.xml

 

and the manifest file is
 AndroidManifest.xml




 
  
   
   
   
  
 


Tested on Real Androd Device [Sony Ericsson (XPERIA)] the output will be like this..


I'd love to hear your thoughts!  

Monday, May 14, 2012

Android Threading (Basic)

Thread
A thread is a sequential path of code execution within a program. And each thread has its own local variables, program counter and lifetime.

in this example we create simplest thread by implementing Runnable interface.


Start Coding.. so lets move ahead with some coding..

create a Simple Android App Name "AndroidThreadingBasic" with 2.3.3 SDK,

your Activity should be like this.

 
package com.rdc;

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

public class MyActivity extends Activity implements OnClickListener {
    
 //Declear the button and Textview instance variable
 private Button btnStart=null; 
 private TextView tv=null;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //get the id of Button from xml file
        btnStart = (Button) findViewById(R.id.button1);
        btnStart.setOnClickListener(this);
        
      //get the id of TextView from xml file
        tv = (TextView) findViewById(R.id.textView1);
        tv.setVisibility(View.INVISIBLE);
        
        
    }

 public void onClick(View v) {
  if(v==btnStart){ 
   
    tv.setVisibility(View.VISIBLE);
   
    // create thread by implementing Runnable interface
    new Thread(new Runnable() {
    
          public void run() {
          System.out.println("Thread is running now..");
             
          for(int i=1;i<=10;i++){
             System.out.println(i);
             }
          }
          
      }).start();  
   
  }
  
 }
}

Now put this code in your main.xml file

    
        
    
            
    



The output Screen will be like this..

and check your logcat, it will print 1 to 10 integers with message.

Note : if you want to update UI then you should use Handler or AsyncTask Thread Check my Blogs below

Android Threading with Handler and  

Android Threading With AsyncTask



I'd love to hear your thoughts! 

Thursday, May 3, 2012

Calculate Device Moving Speed Programmatically

so this evening i would like to share with you new thing what i have learn..

some time we need to calculate moving speed of our android mobile device.

this example will calculate the location coordinates latitude-longitude after every 5 seconds gap.
and then calculate the speed of device in m/s.
all work done in background by the service.

so i we need to do is install this app into mobile and close now it started a background service
and calculate the speed forever..
[you can create without any activity also, but i have created an activity ans started the service from activity]

let's begin the coding, first of all we need to create a simple project having single activity like this
DeviceMovingSpeed.java
  
package com.rdc;

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

public class DeviceMovingSpeed extends Activity// implements Runnable
{
    /** Called when the activity is first created. */
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.v("Debug", "Activity started..");
        Intent myIntent=new Intent(this,MyService.class);  
  startService(myIntent);  
    } 
}

Now we need to create a service where we will handle all the stuff creating a thread Getting current location calculating coordinates latitude-longitude calculating distance and device moving speed
MyService.java
  
package com.rdc;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service
{ 
 private LocationManager locManager;
 private LocationListener locListener = new myLocationListener();
 static final Double EARTH_RADIUS = 6371.00;
 
 private boolean gps_enabled = false;
 private boolean network_enabled = false;
 
 private Handler handler = new Handler();
 Thread t;
 
   @Override
   public IBinder onBind(Intent intent) {return null;}
   @Override
   public void onCreate() {}
   @Override
   public void onDestroy() {}
   @Override
   public void onStart(Intent intent, int startid) {}   
   @Override
 public int onStartCommand(Intent intent, int flags, int startId){
 
 Toast.makeText(getBaseContext(), "Service Started", Toast.LENGTH_SHORT).show();
   
 final Runnable r = new Runnable()
 {   public void run() 
     {
   Log.v("Debug", "Hello");
   location();
   handler.postDelayed(this, 5000);
     }
 };
  handler.postDelayed(r, 5000);  
       return START_STICKY; 
 }
   
   public void location(){
 locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  
 try{
 gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
 }
 catch(Exception ex){}
 try{
 network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);    
 }
 catch(Exception ex){}
 Log.v("Debug", "in on create.. 2");   
 if (gps_enabled) {
 locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locListener);
 Log.v("Debug", "Enabled..");
 }
 if (network_enabled) {
 locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locListener);
 Log.v("Debug", "Disabled..");
 }
 Log.v("Debug", "in on create..3");
 }   
 
   private class myLocationListener implements LocationListener
   {
      double lat_old=0.0;
      double lon_old=0.0;
      double lat_new;
      double lon_new;
      double time=10;
      double speed=0.0;
      @Override
 public void onLocationChanged(Location location) {   
 Log.v("Debug", "in onLocation changed..");   
 if(location!=null){    
 locManager.removeUpdates(locListener);    
 //String Speed = "Device Speed: " +location.getSpeed();
 lat_new=location.getLongitude();
 lon_new =location.getLatitude();
 String longitude = "Longitude: " +location.getLongitude();
 String latitude = "Latitude: " +location.getLatitude();    
 double distance =CalculationByDistance(lat_new, lon_new, lat_old, lon_old);    
 speed = distance/time;     
 Toast.makeText(getApplicationContext(), longitude+"\n"+latitude+"\nDistance is: "
   +distance+"\nSpeed is: "+speed , Toast.LENGTH_SHORT).show();
 lat_old=lat_new;
 lon_old=lon_new;
 }
 }
 @Override
 public void onProviderDisabled(String provider) {}
 @Override
 public void onProviderEnabled(String provider) {}
 @Override
 public void onStatusChanged(String provider, int status, Bundle extras) {}    
   }   
   
   public double CalculationByDistance(double lat1, double lon1, double lat2, double lon2) {
  double Radius = EARTH_RADIUS;
  double dLat = Math.toRadians(lat2-lat1);  
  double dLon = Math.toRadians(lon2-lon1);  
  double a = Math.sin(dLat/2) * Math.sin(dLat/2) +  
  Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *  
  Math.sin(dLon/2) * Math.sin(dLon/2);  
  double c = 2 * Math.asin(Math.sqrt(a));  
  return Radius * c;
   }   
}

now come to AndroidManifest.xml
  


    


    
        
            
                
                
            
                
        
   
           
              
              
           
      
    


okay!! that's it.. now run the application toast will appear to say :-
"current coordinates"
"distance if device is moving"
"and speed of device in m/s (meter/seconds)"

 cheers!!

 I'd love to hear your thoughts!

Friday, April 27, 2012

How to Make a Phone Call Programmatically in Android

 -------------------------------------------
App Name: MakeACall
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.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MyActivity extends Activity implements OnClickListener {

 private Button btncall = null;

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

  btncall = (Button) findViewById(R.id.btnCall);
  btncall.setOnClickListener(this);
 }

 @Override
 public void onClick(View v) {
  String mobileNo = "+919741817902";
  String uri = "tel:" + mobileNo.trim();
  Intent intent = new Intent(Intent.ACTION_CALL);
  intent.setData(Uri.parse(uri));
  startActivity(intent);
 }
}

main.xml

 


AndroidManifest.xml

 





 
 
 
 





The output Screen will be like this..


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

 cheers!!

 I'd love to hear your thoughts!

Sunday, April 15, 2012

Start Service from Activity


Some time we need to start a service from Android Activity..
how can we achieve this i am going to write step by step.

First of all we need to Create a simple application with an Activity

-------------------------------------------
App Name: Activity2Service
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.util.Log;
import android.widget.Toast;

public class MyActivity extends Activity {

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

  Log.v("Debug", "Activity has been Started..");
  Toast.makeText(getBaseContext(), 
                      "Activity Started", Toast.LENGTH_SHORT)
    .show();
  Intent myIntent = new Intent(getBaseContext(), MyService.class);
  startService(myIntent);
 }
}

Then Create a Service
  
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 intent) {
  return null;
 }

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

 @Override
 public void onDestroy() {
  // code to execute when the service is shutting down
 }

 // This method has been deprecated since API 5
 /*
   @Override public void onStart(Intent intent, int startid) { 
          code to execute when the service is starting up
    }*/
  

 @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();
  // We want this service to continue running until it's explicitly
  // stopped, so return sticky.
  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>


Don't forget to make entry in "Manifest" file for Service
  
<?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="8" />

 <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">
   <intent-filter>
    <action android:name="com.rdc.MyService">
    </action>
   </intent-filter>
  </service>

 </application>

</manifest>

Now Run Application, Toast will appear..  :)

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

cheers!!

I'd love to hear your thoughts!

Saturday, April 7, 2012

Start Activity from Activity


Some time we need to start an Activity from Activity..
how can we achieve this i am going to write step by step.

We will create very simple app to do this work
 -------------------------------------------
App Name: Activity2Activity
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: FirstActivity
-------------------------------------------


FirstActivity.java

package com.rdc;

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

public class FirstActivity extends Activity implements OnClickListener {
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.first);

  Button btnload = (Button) findViewById(R.id.btnfirst);
  btnload.setOnClickListener(this);

 }

 @Override
 public void onClick(View v) {
  Intent i = new Intent(FirstActivity.this, SecondActivity.class);
  startActivity(i);
 }
}

SecondActivity.java
package com.rdc;

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

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

  Button btnload = (Button) findViewById(R.id.btnsecond);
  btnload.setOnClickListener(this);

 }

 @Override
 public void onClick(View v) {
  Intent i = new Intent(SecondActivity.this, FirstActivity.class);
  startActivity(i);
 }
}

first.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:text="I am first activity.."
  android:gravity="center"
  android:layout_height="62dp" />
 <LinearLayout
  android:id="@+id/layV"
  android:orientation="vertical"
  android:gravity="center"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Button
   android:text="Load Second Activity"
   android:layout_height="wrap_content"
   android:layout_width="wrap_content"
   android:id="@+id/btnfirst"></Button>
 </LinearLayout>

</LinearLayout>



second.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:text="I am Second activity.."
  android:gravity="center"
  android:layout_height="62dp" />
 <LinearLayout
  android:id="@+id/layV"
  android:orientation="vertical"
  android:gravity="center"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Button
   android:text="Load First Activity"
   android:layout_height="wrap_content"
   android:layout_width="wrap_content"
   android:id="@+id/btnsecond"></Button>
 </LinearLayout>

</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=".FirstActivity"
   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=".SecondActivity"
   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 : Activity2Activity

 cheers!!

 I'd love to hear your thoughts!

Sunday, April 1, 2012

Start BroadcastReceiver from Activity

Some time we need to start a service from Android Activity..
how can we achieve this i am going to write step by step.

We will create very simple app to do this work
 -------------------------------------------
App Name: Activity2BReceiver
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.os.Bundle;
import android.util.Log;

public class MyActivity extends Activity {   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.v("Debug", "Activity has been started..");
    }
}

Then Create a Broadcast Receiver

MyReceiver.java
  
package com.rdc;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
  Log.v("Debug", "SMS Broadcast Receiver has been started..");
  Toast.makeText(context, "BReceiver is watching ur message..", 
    Toast.LENGTH_SHORT).show();

 }

}

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>


Don't forget to make entry in "Manifest" file for Receiver
  
<?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" />
 <uses-permission android:name="android.permission.RECEIVE_SMS">
 </uses-permission>
 <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>
  <receiver android:name="com.rdc.MyReceiver">

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

 </application>
</manifest>

Run this app and send message from another mobile/emulator, Receiver will notify you about new sms
See below output screens tensted on Emulator and Real Device


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


I'd love to hear your thoughts!

Saturday, March 31, 2012

How to Get Own Mobile Number Programmatically

sometime you have multiple SIM cards and you don't know which one Number you are using.Then you may be want to "Get Own Mobile Number" ?
How I am going to write a small android application which will solve our puzzle.

So here we go.. we need to create a Basic Android App having an Activity like this
GetMyPhoneNoActivity.java
  
package com.kns;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class GetMyPhoneNoActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
    
        String number =getMyPhoneNO();
        Toast.makeText(getApplicationContext(), "My Phone No is: "
        +number, Toast.LENGTH_SHORT).show();
        Log.v("Debug", number);        
    }
    
    private String getMyPhoneNO(){
     TelephonyManager mTelephonyMgr;  
     mTelephonyMgr = (TelephonyManager) getSystemService
       (Context.TELEPHONY_SERVICE);   

     String yourNumber = mTelephonyMgr.getLine1Number();
  return yourNumber; 
    }     
}

Then we need to add user permission into manifest file
  

so it will be look like this..
AndroidManifest.xml
  


    

 

    
        
            
                
                
            
        

    


Now if will check this code on Emulator device, The output will be..


Note: As i have read, so far some people have conflict about different behavior of  output.
there are reports that some SIMs cause this method to return null.

Because --? I think there are cases where the phone does not know its own number - it somehow depends on the network provider / SIM card.

So, There is no guaranteed solution to this problem because the phone number is not physically stored on all SIM-cards, or broadcasted from the network to the phone. This is especially true in some countries which requires physical address verification, with number assignment only happening afterwards. Phone number assignment happens on the network - and can be changed without changing the SIM card or device (e.g. this is how porting is supported).

I'd like to know your suggestions!!

Thanks!