Tuesday 17 September 2013

Calculate distance between two points latitude and longitude in Android

Use this method with following parameters

public double Calculate_Distance(Double latB, Double longB,
            Double latA, Double longA) {
        double distance;
        Location locationA = new Location("point A");
        locationA.setLatitude(latA);
        locationA.setLongitude(longA);
        Location locationB = new Location("point B");
        locationB.setLatitude(latB);
        locationB.setLongitude(longB);
        distance = locationA.distanceTo(locationB);
        return distance;
    }

Constructs the new Location with a named provider.


Then use this below code in your activity


Double total_distance = Calculate_Distance(latB,longB, latA,
                                                longA);

Returns the approximate distance in meters between this location.

Thursday 5 September 2013

Using external font in Android Typeface Example

Loading external fonts in android is very easy

1.Add your external fonts in assets folder 

2.Create  a Class Typeface_Utils

import android.app.Activity;
import android.graphics.Typeface;

public class Typeface_Utils {
   
    static Typeface tf;
    public static void Typeface_font(Activity activity)
    {
        //add new font and use it .settypeface(tf);
        tf = Typeface.createFromAsset(activity.getAssets(),"abc.ttf");
    }
}

3.Then we will create the layout as follows:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >


    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Typeface_Sample"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

4.Then in your MainActivity.

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

public class MainActivity extends Activity {

    TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        tv = (TextView)findViewById(R.id.textView1);
        Typeface_Utils.Typeface_font(MainActivity.this);
        tv.setTypeface(Typeface_Utils.tf);
    }

}






Send and recieve SMS in Android Sample Code

In android you can use SMSManager ,Manages SMS operations such as sending data, text, and pdu SMS messages. Get this object by calling the static method SmsManager.getDefault(). 

SmsManager API
SmsManager smsManager = SmsManager.getDefault();
 smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
 
1.First  create a simple activity called as MainActivity, then we will create the layout as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Enter the phone number of recipient"
        />    
    <EditText
        android:id="@+id/txtPhoneNo" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"       
        />
    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"        
        android:text="Message"
        />    
    <EditText
        android:id="@+id/txtMessage" 
        android:layout_width="fill_parent"
        android:layout_height="150px"
        android:gravity="top"        
        />         
    <Button
        android:id="@+id/btnSendSMS" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send SMS"
        />   
</LinearLayout>

2. The code for the activity is as follows





public class MainActivity extends Activity
{
    Button btnSendSMS;
    EditText txtPhoneNo;
    EditText txtMessage;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);       
        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
        txtMessage = (EditText) findViewById(R.id.txtMessage);
       
        /*
        Intent sendIntent = new Intent(Intent.ACTION_VIEW);
        sendIntent.putExtra("sms_body", "Content of the SMS goes here...");
        sendIntent.setType("vnd.android-dir/mms-sms");
        startActivity(sendIntent);
        */
               
        btnSendSMS.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {               
                String phoneNo = txtPhoneNo.getText().toString();
                String message = txtMessage.getText().toString();                
                if (phoneNo.length()>0 && message.length()>0)               
                    sendSMS(phoneNo, message);               
                else
                    Toast.makeText(getBaseContext(),
                        "Please enter both phone number and message.",
                        Toast.LENGTH_SHORT).show();
            }
        });       
    }
   
    //---sends a SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {     
        /*
        PendingIntent pi = PendingIntent.getActivity(this, 0,
                new Intent(this, test.class), 0);               
            SmsManager sms = SmsManager.getDefault();
            sms.sendTextMessage(phoneNumber, null, message, pi, null);       
        */
       
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";
       
        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);
       
        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);
       
        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));
       
        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered",
                                Toast.LENGTH_SHORT).show();
                        break;                       
                }
            }
        }, new IntentFilter(DELIVERED));       
       
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);              
    }   
}

3.The code for the SmsReceiver  BroadcastReceiver is as follows 

Create a class which extends BroadcastReceiver, which override the onRecieve Method.In the onRecieve method, remove the data from the received Intent, remove the SmsMessage object, and obtain the sender’s address and text to display on a toast.





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

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

4.Add the following in manifest file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sms_sample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    <uses-permission android:name="android.permission.READ_SMS"/>
    <uses-permission android:name="android.permission.WRITE_SMS"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Now , run the app in your device to test and you can use the above sms code in your next  Android app.
 

Wednesday 4 September 2013

Get device details in android (TelephonyManager)

1.Create a class SystemStatus_Utils

import android.content.Context;
import android.telephony.TelephonyManager;

public class SystemStatus_Utils {

    public static String fetch_tel_status(Context cx) {
        String result = null;
        TelephonyManager tm = (TelephonyManager) cx
            .getSystemService(Context.TELEPHONY_SERVICE);//
        String str = "";
        str += "DeviceId(IMEI) = " + tm.getDeviceId() + "\n";
        str += "DeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion()
            + "\n"; 
        str += "Line1Number = " + tm.getLine1Number() + "\n";
        str += "NetworkCountryIso = " + tm.getNetworkCountryIso() + "\n";
        str += "NetworkOperator = " + tm.getNetworkOperator() + "\n";
        str += "NetworkOperatorName = " + tm.getNetworkOperatorName() + "\n";
        str += "NetworkType = " + tm.getNetworkType() + "\n";
        str += "PhoneType = " + tm.getPhoneType() + "\n";
        str += "SimCountryIso = " + tm.getSimCountryIso() + "\n";
        str += "SimOperator = " + tm.getSimOperator() + "\n";
        str += "SimOperatorName = " + tm.getSimOperatorName() + "\n";
        str += "SimSerialNumber = " + tm.getSimSerialNumber() + "\n";
        str += "SimState = " + tm.getSimState() + "\n";
        str += "SubscriberId(IMSI) = " + tm.getSubscriberId() + "\n";
        str += "VoiceMailNumber = " + tm.getVoiceMailNumber() + "\n";

        int mcc = cx.getResources().getConfiguration().mcc;
        int mnc = cx.getResources().getConfiguration().mnc;
        str += "IMSI MCC (Mobile Country Code):" + String.valueOf(mcc) + "\n";
        str += "IMSI MNC (Mobile Network Code):" + String.valueOf(mnc) + "\n";
        result = str;
        return result;
      }
}

2.Use in your MainActivity

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

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
    String strinfo =    SystemStatus_Utils.fetch_tel_status(MainActivity.this);
        System.out.println("INFO : "+strinfo);
    }

}


3.Add permission in manifest file

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

Andorid Service Example Code


 A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors). 

1.Create a Service Class MyService

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

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
   
   
    @Override
    public void onCreate() {
        Toast.makeText(this, "New Service Created", Toast.LENGTH_LONG).show();
      
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // For time consuming an long tasks you can launch a new thread here...
        Toast.makeText(this, " Service Start", Toast.LENGTH_LONG).show();
      
  
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
       
    }
}

2.Create a Class where you can start service and stop service.

public class MainActivity extends Activity {

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

    // Start the  service
    public void startNewService(View view) {
       
        startService(new Intent(this, MyService.class));
    }

    // Stop the  service
    public void stopNewService(View view) {
       
        stopService(new Intent(this, MyService.class));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

3.Add Service to your manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.service.sample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.service.sample.MainActivity"
            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:name="com.service.sample.MyService"
            android:enabled="true"
            android:exported="true" >
        </service>
    </application>

</manifest>

Now the service handling requests is done outside of the main thread, the application remains responsive to the user and the Android system. 

Tuesday 3 September 2013

Android Proximity Sensors Sample Code

1.Create a Class MainActivity 

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

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

 TextView ProximitySensor, ProximityMax, ProximityReading;

 SensorManager mySensorManager;
 Sensor myProximitySensor;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ProximitySensor = (TextView)findViewById(R.id.textView1);
        ProximityMax = (TextView)findViewById(R.id.textView2);
        ProximityReading = (TextView)findViewById(R.id.textView3);
       // Now in the SensorActivity we access the device sensor using SensorManager, an instance of this class is got by calling getSystemService(SENSOR_SERVICE) . We implement the class with theSensorEventListener interface to override its methods to do actions on sensor value change.
        mySensorManager = (SensorManager)getSystemService(
          Context.SENSOR_SERVICE);
        myProximitySensor = mySensorManager.getDefaultSensor(
          Sensor.TYPE_PROXIMITY);
       
        if (myProximitySensor == null){
         ProximitySensor.setText("No Proximity Sensor!");
        }else{
         ProximitySensor.setText(myProximitySensor.getName());
         ProximityMax.setText("Maximum Range: "
           + String.valueOf(myProximitySensor.getMaximumRange()));
         mySensorManager.registerListener(proximitySensorEventListener,
           myProximitySensor,
           SensorManager.SENSOR_DELAY_NORMAL);
        }
    }
   
    SensorEventListener proximitySensorEventListener
    = new SensorEventListener(){

  @Override
  public void onAccuracyChanged(Sensor sensor, int accuracy) {
   // TODO Auto-generated method stub
  
  }

  @Override
  public void onSensorChanged(SensorEvent event) {
   // TODO Auto-generated method stub

   if(event.sensor.getType()==Sensor.TYPE_PROXIMITY)
   {
    ProximityReading.setText("Proximity Sensor Reading:"
      + String.valueOf(event.values[0]));
  
  
   }
  }
    };
}

2.Create a layout 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="32dp"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView2"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Android Accelerometer Sensors Sample Code

The Android platform supports three broad categories of sensors:

  • Motion sensors These sensors measure acceleration forces and rotational forces along three axes. This category includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.
  • Environmental sensors These sensors measure various environmental parameters, such as ambient air temperature and pressure, illumination, and humidity. This category includes barometers, photometers, and thermometers.
  • Position sensors These sensors measure the physical position of a device. This category includes orientation sensors and magnetometers.

The accelerometer is a hardware sensor in android  used to detect a motion,
Measures the acceleration force in m/s2 that is applied to a device on all three physical axes (x, y, and z), including the force of gravity.

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity 
{
    private SensorManager sensorManager;
    private Sensor sensor;
    private int x, y, z;
    TextView tv;
   
    /** Called when the activity is first created. */
 
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv=(TextView)findViewById(R.id.textView1);
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensor = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
    }
   
    private void refreshDisplay()
    {
        String output = String
                .format("x is: %d / y is: %d / z is: %d", x, y, z);
        tv.setText(output);
    }
   
    @Override
    protected void onResume()
    {
        super.onResume();
        sensorManager.registerListener(accelerationListener, sensor,
                SensorManager.SENSOR_DELAY_GAME);
    }
  
    @Override
    protected void onStop()
    {
        sensorManager.unregisterListener(accelerationListener);
        super.onStop();
      
    }

   
    private SensorEventListener accelerationListener = new SensorEventListener()
    {
        @Override
        public void onAccuracyChanged(Sensor sensor, int acc)
        {
        }

      
        @Override
        public void onSensorChanged(SensorEvent event) {
            // TODO Auto-generated method stub
            x = (int) event.values[0];
            y = (int) event.values[1];
            z = (int) event.values[2];
          
            refreshDisplay();
        }
         };
      
} 

Create a layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>
 

 

Send a Mail in Android programmatically

1.Create a Class Mail_Utils

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

public class Mail_Utils {

    /**
     * @param address
     * @param subject
     * @param emailbody
     * @param activity
     * Function to send a e-mail.
     */
    public static void sendEmail(String address,String subject,String emailbody,Activity activity){
       
        if(!address.trim().equalsIgnoreCase("")){
          final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
          emailIntent.setType("plain/text");
          emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, address);
          emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
          emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailbody);
          activity.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
        }
        else{
            Toast.makeText(activity, "Please enter an email address..", Toast.LENGTH_LONG).show();
        }
      }
   
}

2.Use this in your MainActivity



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

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Mail_Utils.sendEmail("nikhil.v@xyz.com", "Test", "Hiii",MainActivity.this);
    }

}

Now, are able to Send a Mail in Android programmatically.

Fragments android support for lower android versions

1.Download a jar file "android-support-v4.jar" and add it to libs folder and set the path in project
then create a MainActivity

 public class MainActivity extends FragmentActivity  {

    Button b1,b2,b3;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        b1 = (Button)findViewById(R.id.button1);
        b2 = (Button)findViewById(R.id.button2);
        b3 = (Button)findViewById(R.id.button3);
       
        b1.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
           
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager
                        .beginTransaction();
                First first_act = new First();

                fragmentTransaction.replace(R.id.fragment_container,
                        first_act);
                fragmentTransaction.addToBackStack("first_act");
                fragmentTransaction.commit();
               
            }
        });
        b2.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
           
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager
                        .beginTransaction();
                Second sec_act = new Second();

                fragmentTransaction.replace(R.id.fragment_container,
                        sec_act);
                fragmentTransaction.addToBackStack("sec_act");
                fragmentTransaction.commit();
               
            }
        });
 b3.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
           
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager
                        .beginTransaction();
                Third third_act = new Third();

                fragmentTransaction.replace(R.id.fragment_container,
                        third_act);
                fragmentTransaction.addToBackStack("third_act");
                fragmentTransaction.commit();
               
            }
        });
    }

}
2.Create a layout  activity_main

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="100dp"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:text="Button" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/button1"
            android:layout_marginTop="14dp"
            android:text="Button" />

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/button2"
            android:layout_marginTop="22dp"
            android:text="Button" />
    </RelativeLayout>



    <RelativeLayout
        android:id="@+id/fragment_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/relativeLayout1" >

    </RelativeLayout>

</RelativeLayout>

3.Create a Class First and layout

public class First extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        /** Inflating the layout for this fragment **/
        View v = inflater.inflate(R.layout.first, null);
        return v;
    }
}

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


    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="First"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

4.Create a Class Second and layout

public class Second extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        /** Inflating the layout for this fragment **/
        View v = inflater.inflate(R.layout.second, null);
        return v;
    }
}

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


    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Second"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

5. Create a Class Third and layout

public class Third extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        /** Inflating the layout for this fragment **/
        View v = inflater.inflate(R.layout.third, null);
        return v;
    }
}

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


    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Third "
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

Custom Dialog box in Android

1.Create a Class Dialog_Utils

public class Dialog_Utils {

    /**
     * to display dialog
     * @param context
     * @param title
     * @param message
     * @param status
     */
   
    public void show_Dialog(final Context context, String title, String message) {
        final Dialog dialog = new Dialog(context);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setContentView(R.layout.common_dialog);
       
        dialog.getWindow().setBackgroundDrawable(
                new ColorDrawable(android.graphics.Color.TRANSPARENT));
        final TextView txt_tittle = (TextView)dialog.findViewById(R.id.textView1);
        final TextView txt_message = (TextView)dialog.findViewById(R.id.textView2);
        final Button btn_close = (Button)dialog.findViewById(R.id.button1);
       
        txt_tittle.setText(title);
        txt_message.setText(message);
        btn_close.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}


2.Now use these in your MainActivity


public class MainActivity extends Activity {
    // Alert Dialog Manager
        Dialog_Utils dialog = new Dialog_Utils();
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        dialog.show_Dialog(MainActivity.this, "Tittle",
                "MESSAGE/SUBJECT");
    }

}


Now, are able to create acustom dialog android application.

Check network Connection status in Android

1.Create a Connection_Utils

public class Connection_Utils {

    private Context _context;

    public Connection_Utils(Context context){
        this._context = context;
    }

    /**
     * Checking for all possible internet connections
     * @return
     * **/
    public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }

          }
          return false;
    }
}


2. Use this in your MainActivity

 public class MainActivity extends Activity {
    // Connection detector class
        Connection_Utils cd;
        // flag for Internet connection status
        Boolean isInternetPresent = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      
        cd = new Connection_Utils(getApplicationContext());
     // Check if Internet present
        isInternetPresent = cd.isConnectingToInternet();
        if (!isInternetPresent) {
            System.out.println("Connection Error");
            // Internet Connection is not present
            // stop processing code by return
            return;
        }
    }

}


3.Add permission in manifest file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.connectionstatus_sample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
   <!-- Network State Permissions -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- Access Location -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
       <!-- Internet Permissions -->
    <uses-permission android:name="android.permission.INTERNET" />
   
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
   
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>




Camera in Android Example

1.Add these in your Main Activity

public class MainActivity extends Activity {

    private static final int REQ_CAMERA_IMAGE = 456;

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


        String message = "Click the button below to start";
        if(cameraNotDetected()){
            message = "No camera detected, clicking the button below will have unexpected behaviour.";
        }
        TextView cameraDescriptionTextView = (TextView) findViewById(R.id.text_view_camera_description);
        cameraDescriptionTextView.setText(message);
    }

    private boolean cameraNotDetected() {
        return !getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
    }

    @FromXML
    public void onUseCameraClick(View button){
        Intent intent = new Intent(this, CameraActivity.class);
        startActivityForResult(intent, REQ_CAMERA_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == REQ_CAMERA_IMAGE && resultCode == RESULT_OK){
            String imgPath = data.getStringExtra(CameraActivity.EXTRA_IMAGE_PATH);
            Log.i("Got image path: "+ imgPath);
            displayImage(imgPath);
        } else
        if(requestCode == REQ_CAMERA_IMAGE && resultCode == RESULT_CANCELED){
            Log.i("User didn't take an image");
        }
    }

    private void displayImage(String path) {
        ImageView imageView = (ImageView) findViewById(R.id.image_view_captured_image);
        imageView.setImageBitmap(BitmapHelper.decodeSampledBitmap(path, 300, 250));
    }
}

2.Create Class CameraActivity

public class CameraActivity extends Activity implements PictureCallback {

    protected static final String EXTRA_IMAGE_PATH = "EXTRA_IMAGE_PATH";

    private Camera camera;
    private CameraPreview cameraPreview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        setResult(RESULT_CANCELED);
        // Camera may be in use by another activity or the system or not available at all
        camera = getCameraInstance();
        if(cameraAvailable(camera)){
            initCameraPreview();
        } else {
            finish();
        }
    }

    // Show the camera view on the activity
    private void initCameraPreview() {
        cameraPreview = (CameraPreview) findViewById(R.id.camera_preview);
        cameraPreview.init(camera);
    }

    @FromXML
    public void onCaptureClick(View button){
        // Take a picture with a callback when the photo has been created
        // Here you can add callbacks if you want to give feedback when the picture is being taken
        camera.takePicture(null, null, this);
    }

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        Log.d("Picture taken");
        String path = savePictureToFileSystem(data);
        setResult(path);
        finish();
    }

    private static String savePictureToFileSystem(byte[] data) {
        File file = getOutputMediaFile();
        saveToFile(data, file);
        return file.getAbsolutePath();
    }

    private void setResult(String path) {
        Intent intent = new Intent();
        intent.putExtra(EXTRA_IMAGE_PATH, path);
        setResult(RESULT_OK, intent);
    }

    // ALWAYS remember to release the camera when you are finished
    @Override
    protected void onPause() {
        super.onPause();
        releaseCamera();
    }

    private void releaseCamera() {
        if(camera != null){
            camera.release();
            camera = null;
        }
    }
}


3.Create Class CameraPreview

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

    private Camera camera;
    private SurfaceHolder holder;

    public CameraPreview(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public CameraPreview(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CameraPreview(Context context) {
        super(context);
    }

    public void init(Camera camera) {
        this.camera = camera;
        initSurfaceHolder();
    }

    @SuppressWarnings("deprecation") // needed for < 3.0
    private void initSurfaceHolder() {
        holder = getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        initCamera(holder);
    }

    private void initCamera(SurfaceHolder holder) {
        try {
            camera.setPreviewDisplay(holder);
            camera.startPreview();
        } catch (Exception e) {
            Log.d("Error setting camera preview", e);
        }
    }

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

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
    }
}

4.Create Class BitmapHelper 





public class BitmapHelper {

    public static Bitmap decodeSampledBitmap(String path, int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        // Calculate inSampleSize
        options.inSampleSize = BitmapHelper.calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(path, options);
    }

    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }
        }
        return inSampleSize;
    }

}

5.Create Class CameraHelper 


public class CameraHelper {

    public static boolean cameraAvailable(Camera camera) {
        return camera != null;
    }

    public static Camera getCameraInstance() {
        Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e) {
            // Camera is not available or doesn't exist
            Log.d("getCamera failed", e);
        }
        return c;
    }

}

6.Create Class MediaHelper 

public class MediaHelper {

    public static File getOutputMediaFile(){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Spike");
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("failed to create directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile = new File(mediaStorageDir.getPath() + File.separator +"IMG_"+ timeStamp +".jpg");

        return mediaFile;
    }

    public static boolean saveToFile(byte[] bytes, File file){
        boolean saved = false;
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bytes);
            fos.close();
            saved = true;
        } catch (FileNotFoundException e) {
            Log.e("FileNotFoundException", e);
        } catch (IOException e) {
            Log.e("IOException", e);
        }
        return saved;
    }

}

7.Create Class Log

public class Log {

    private static final String TAG = "CameraCheck";

    public static void d(String msg) {
        d(msg, null);
    }

    public static void d(String msg, Throwable e) {
        android.util.Log.d(TAG, Thread.currentThread().getName() + "| " + msg, e);
    }

    public static void i(String msg) {
        i(msg, null);
    }

    public static void i(String msg, Throwable e) {
        android.util.Log.i(TAG, Thread.currentThread().getName() + "| " + msg, e);
    }

    public static void e(String msg) {
        e(msg, null);
    }

    public static void e(String msg, Throwable e) {
        android.util.Log.e(TAG, Thread.currentThread().getName() + "| " + msg, e);
    }

    public static void v(String msg) {
        android.util.Log.v(TAG, Thread.currentThread().getName() + "| " + msg);
    }

    public static String identifyMessage(Resources res, Message msg) {
        try {
            return res.getResourceEntryName(msg.what);
        } catch (NotFoundException ignore) {
            return "not found";
        }
    }

    public static void w(String msg) {
        android.util.Log.w(TAG, Thread.currentThread().getName() + "| " + msg);
    }

    /**
     * Use this when you want to debug a String that is too long to be printed in one Log line.
     * This will print the string breaking it up into 500 character segments
     *
     * @param msg
     */
    public static void debugLongString(String msg) {
        StringBuffer b = new StringBuffer();
        char[] c = msg.toCharArray();
        int x = 0;
        for (int i = 0; i < c.length; i++) {
            b.append(c[i]);
            if (x++ == 500) {
                d(b.toString());
                b = new StringBuffer();
                x = 0;
            }
        }
        d(b.toString());
    }
}

8.Add permission in manifest file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.camera.snap"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.camera.snap.ui.MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.camera.snap.ui.CameraActivity"
            android:label="@string/title_activity_camera"
            android:screenOrientation="landscape"
            android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" />
    </application>

</manifest>

Android Call function programmatically

1.Create a Class Call_Utils

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;

public class Call_Utils {

    /**
     * @param str_phno
     * @param activity
     * Function for calling a contact.
     */
    public static void Call_contact(String str_phno,Activity activity){
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:"
                + str_phno.trim()));
        activity.startActivity(intent);
    }
   
}

2.Use this in your MainActivity



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

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Call_Utils.Call_contact("09123456789", MainActivity.this);
    }
}

3.Add permission in manifest file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.call_sample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
 <!-- Call Phone Permissions -->
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Now,you can use call function programmatically.

Bluetooth Switch On, Off,Device Discoverable,Scan Remote device

1. Create a Class  with name Bluetooth_Utils

import java.util.Set;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.widget.Toast;

public class Bluetooth_Utils {

    private static final int REQUEST_ENABLE_BT = 0;
    private static final int REQUEST_DISCOVERABLE_BT = 0;
    private static BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
   
    public  static void Check_BT_present()
    {
        if (mBluetoothAdapter == null) {
            System.out.println("device not supported");
        }
    }
   
    public static void onBT(Activity activity)
    {
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            activity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }
   
    public static void offBT(Activity activity)
    {
        mBluetoothAdapter.disable();
        CharSequence text = "TURNING_OFF BLUETOOTH";
        int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(activity, text, duration);
        toast.show();
    }
   
    public static void devicediscoverable(Activity activity)
    {
        if (!mBluetoothAdapter.isDiscovering()) {
            CharSequence text = "MAKING YOUR DEVICE DISCOVERABLE";
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(activity, text, duration);
            toast.show();
            Intent enableBtIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            activity.startActivityForResult(enableBtIntent,
                    REQUEST_DISCOVERABLE_BT);

        }
    }
   
    public  static void Scan_NearbyBT()
    {
        // Starting the device discovery
        System.out.println("\nStarting discovery...");
        mBluetoothAdapter.startDiscovery();
        System.out.println("\nDone with discovery...");

        // Listing paired devices
        System.out.println("\nDevices Pared:");
        Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
        for (BluetoothDevice device : devices) {
            System.out.println("\nFound device: " + device.getName());
        }
    }
   
}

2. Use these in your MainActivity

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

public class MainActivity extends Activity {
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
   
        final Button button = (Button) findViewById(R.id.button1);
        final Button button1 = (Button) findViewById(R.id.button2);
        final Button button2 = (Button) findViewById(R.id.button3);
        Bluetooth_Utils.Check_BT_present();
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
           
                Bluetooth_Utils.onBT(MainActivity.this);
            }
        });
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Bluetooth_Utils.devicediscoverable(MainActivity.this);
                Bluetooth_Utils.Scan_NearbyBT();
                }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
               
                Bluetooth_Utils.offBT(MainActivity.this);
            }
        });
    }

}

3.Create a layout activity_main

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/ic_launcher"
    tools:context=".MainActivity" >

<TextView android:text="" android:id="@+id/out" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="49dp"
        android:text="switch on" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="27dp"
        android:text="make device discoverable and device scan " />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button2"
        android:layout_below="@+id/button2"
        android:layout_marginTop="28dp"
        android:text="switch off" />

</RelativeLayout>

4.Add permissions in manifest file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bluetooth.sample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Now, are able to Switch On, Off,Device Discoverable,Scan Remote deviceusing bluetooth.