Android Wi-Fi Tutorial

Android allows applications to access to view the access the state of the wirless connections at very low level. Application can access almost all the information of a wifi connection.
The information that an application can access includes connected network's link speed,IP address, negotiation state, other networks information. Applications can also scan, add, save, terminate and initiate Wi-Fi connections.
Android provides WifiManager API to manage all aspects of WIFI connectivity. We can instantiate this class by calling getSystemService method. Its syntax is given below:
WifiManager mainWifiObj;
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
In order to scan a list of wireless networks, you also need to register your BroadcastReceiver. It can be registered using registerReceiver method with argument of your reciever class object. Its sytanx is given below:
class WifiScanReceiver extends BroadcastReceiver {
   public void onReceive(Context c, Intent intent) {
   }
}
WifiScanReceiver wifiReciever = new WifiScanReceiver();
registerReceiver(wifiReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));  
The wifi scan can be start by calling the startScan method of the WifiManager class. This method returns a list of ScanResult objects. You can access any object by calling the get method of list. Its syntax is given below:
List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
String data = wifiScanList.get(0).toString();
Apart from just Scanning , you can have more control over your WIFI by using the methods defined in WifiManager class. They are listed as follows:
Sr.NoMethod & Description
1addNetwork(WifiConfiguration config)
This method add a new network description to the set of configured networks.
2createWifiLock(String tag)
This method creates a new WifiLock.
3disconnect()
This method disassociate from the currently active access point.
4enableNetwork(int netId, boolean disableOthers)
This method allow a previously configured network to be associated with.
5getWifiState()
This method gets the Wi-Fi enabled state
6isWifiEnabled()
This method return whether Wi-Fi is enabled or disabled.
7setWifiEnabled(boolean enabled)
This method enable or disable Wi-Fi.
8updateNetwork(WifiConfiguration config)
This method update the network description of an existing configured network.

Example

Here is an example demonstrating the use of WIFI. It creates a basic application that scans a list of wirless networks and populate them in a list view.
To experiment with this example , you need to run this on an actual device on which wifi is turned on.
StepsDescription
1You will use Eclipse IDE to create an Android application and name it as WIFI under a package com.example.wifi. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add WebView code.
3Modify the res/layout/activity_main to add respective XML components
4Modify the AndroidManifest.xml to add the necessary permissions
5Run the application and choose a running android device and install the application on it and verify the results.
Following is the content of the modifed main activity file src/com.example.wifi/MainActivity.java.
package com.example.wifi;

import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

   WifiManager mainWifiObj;
   WifiScanReceiver wifiReciever;
   ListView list;
   String wifis[];
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      list = (ListView)findViewById(R.id.listView1);
      mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
      wifiReciever = new WifiScanReceiver();
      mainWifiObj.startScan();
   }


   protected void onPause() {
      unregisterReceiver(wifiReciever);
      super.onPause();
   }

   protected void onResume() {
      registerReceiver(wifiReciever, new IntentFilter(
      WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
      super.onResume();
   }

   class WifiScanReceiver extends BroadcastReceiver {
      @SuppressLint("UseValueOf")
      public void onReceive(Context c, Intent intent) {
         List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
         wifis = new String[wifiScanList.size()];
         for(int i = 0; i < wifiScanList.size(); i++){
            wifis[i] = ((wifiScanList.get(i)).toString());
         }

         list.setAdapter(new ArrayAdapter<String>(getApplicationContext(),
         android.R.layout.simple_list_item_1,wifis));
      }
   }

}
Following is the modified content of the xml res/layout/activity_main.xml.
<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:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >

   <ListView
      android:id="@+id/listView1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:drawSelectorOnTop="false"
      android:background="@android:color/background_dark"
      android:listSelector="@android:color/darker_gray" >

   </ListView>
</RelativeLayout>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.wifi"
   android:versionCode="1"
   android:versionName="1.0" >

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

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

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      <activity
         android:name="com.example.wifi.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>
    <activity
         android:name="com.example.wifi.ListWifiActivity"
         android:label="@string/title_activity_list_wifi" >
      </activity>
   </application>
</manifest>

Let's try to run your WIFI application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.
Anroid Wi-Fi Tutorial Select your mobile device as an option and then check your mobile device which will display your mobile screen filled with wireless networks around you. It is shown below:
Anroid Wi-Fi Tutorial Note the information that has been returned to you. It contains much information about each of the wireless network detected.

Android XML Parser Tutorial

XML stands for Extensible Markup Language.XML is a very popular format and commonly used for sharing data on the internet. This chapter explains how to parse the XML file and extract necessary information from it.
Android provides three types of XML parsers which are DOM,SAX and XMLPullParser. Among all of them android recommend XMLPullParser because it is efficent and easy to use. So we are going to use XMLPullParser for parsing XML
The first step is to identify the fields in the XML data in which you are interested in. For example. In the XML given below we interested in getting temperature only.
<?xml version="1.0"?>
<current>
   <city id="2643743" name="London">
      <coord lon="-0.12574" lat="51.50853"/>
      <country>GB</country>
      <sun rise="2013-10-08T06:13:56" set="2013-10-08T17:21:45"/>
   </city>
   <temperature value="289.54" min="289.15" max="290.15" unit="kelvin"/>
   <humidity value="77" unit="%"/>
   <pressure value="1025" unit="hPa"/>
</country>

XML - Elements

An xml file consist of many components. Here is the table defining the compoents of an XML file and their description.
Sr.NoComponent & description
1Prolog
An XML file starts with a prolog. The first line that contains the information about a file is prolog
2Events
An XML file has many events. Event could be like this. Document starts , Document ends, Tag start , Tag end and Text e.t.c
3Text
Apart from tags and events , and xml file also contains simple text. Such as GB is a text in the country tag.
4Attributes
Attributes are the additional properties of a tag such as value e.t.c

XML - Parsing

In the next step , we will create XMLPullParser object , but in order to create that we will first create XmlPullParserFactory object and then call its newPullParser() method to create XMLPullParser. Its syntax is given below:
private XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance();
private XmlPullParser myparser = xmlFactoryObject.newPullParser();
The next step involves specifying the file for XmlPullParser that contains XML. It could be a file or could be a Stream. In our case it is a stream.Its syntax is given below:
myparser.setInput(stream, null);
The last step is to parse the XML. An XML file consist of events , Name , Text , AttributesValue e.t.c. So XMLPullParser has a seperate function for parsing each of the component of XML file. Its syntax is given below:
int event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) 
{
   String name=myParser.getName();
   switch (event){
      case XmlPullParser.START_TAG:
      break;
      case XmlPullParser.END_TAG:
      if(name.equals("temperature")){
         temperature = myParser.getAttributeValue(null,"value");
      }
      break;
   }		 
   event = myParser.next(); 					
}
The method getEventType returns the type of event that happens. e.g: Document start , tag start e.t.c. The method getName returns the name of the tag and since we are only interested in temperature , so we just check in conditional statement that if we got a temperature tag , we call the method getAttributeValue to return us the value of temperature tag.
Apart from the these methods , there are other methods provided by this class for better parsing XML files. These methods are listed below:
Sr.NoMethod & description
1getAttributeCount()
This method just Returns the number of attributes of the current start tag
2getAttributeName(int index)
This method returns the name of the attribute specified by the index value
3getColumnNumber()
This method returns the Returns the current column number, starting from 0.
4getDepth()
This method returns Returns the current depth of the element.
5getLineNumber()
Returns the current line number, starting from 1.
6getNamespace()
This method rReturns the namespace URI of the current element.
7getPrefix()
This method returns the prefix of the current element
8getName()
This method returns the name of the tag
9getText()
This method returns the text for that particular element
10isWhitespace()
This method checks whether the current TEXT event contains only whitespace characters.

Example

Here is an example demonstrating the use of XMLPullParser class. It creates a basic Weather application that allows you to parse XML from google weather api and show the result.
To experiment with this example , you can run this on an actual device or in an emulator.
StepsDescription
1You will use Eclipse IDE to create an Android application and name it as XMLParser under a package com.example.xmlparser. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add necessary code.
3Modify the res/layout/activity_main to add respective XML components
4Modify the res/values/string.xml to add necessary string components
5Create a new java file under src/HandleXML.java to fetch and parse XML data
6Modify AndroidManifest.xml to add necessary internet permission
7Run the application and choose a running android device and install the application on it and verify the results
Following is the content of the modifed main activity file src/com.example.xmlparser/MainActivity.java.
package com.example.xmlparser;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {

   private String url1 = "http://api.openweathermap.org/data/2.5/weather?q=";
   private String url2 = "&mode=xml";
   private EditText location,country,temperature,humidity,pressure;
   private HandleXML obj;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      location = (EditText)findViewById(R.id.editText1);
      country = (EditText)findViewById(R.id.editText2);
      temperature = (EditText)findViewById(R.id.editText3);
      humidity = (EditText)findViewById(R.id.editText4);
      pressure = (EditText)findViewById(R.id.editText5);
   }

   @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;
   }

   public void open(View view){
      String url = location.getText().toString();
      String finalUrl = url1 + url + url2;
      country.setText(finalUrl);
      obj = new HandleXML(finalUrl);
      obj.fetchXML();
      while(obj.parsingComplete);
      country.setText(obj.getCountry());
      temperature.setText(obj.getTemperature());
      humidity.setText(obj.getHumidity());
      pressure.setText(obj.getPressure());

   }

}
Following is the content of src/com.example.xmlparser/HandleXML.java.
package com.example.xmlparser;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;


public class HandleXML {

   private String country = "county";
   private String temperature = "temperature";
   private String humidity = "humidity";
   private String pressure = "pressure";
   private String urlString = null;
   private XmlPullParserFactory xmlFactoryObject;
   public volatile boolean parsingComplete = true;
   public HandleXML(String url){
      this.urlString = url;
   }
   public String getCountry(){
      return country;
   }
   public String getTemperature(){
      return temperature;
   }
   public String getHumidity(){
      return humidity;
   }
   public String getPressure(){
      return pressure;
   }

   public void parseXMLAndStoreIt(XmlPullParser myParser) {
      int event;
      String text=null;
      try {
         event = myParser.getEventType();
         while (event != XmlPullParser.END_DOCUMENT) {
            String name=myParser.getName();
            switch (event){
               case XmlPullParser.START_TAG:
               break;
               case XmlPullParser.TEXT:
               text = myParser.getText();
               break;

               case XmlPullParser.END_TAG:
                  if(name.equals("country")){
                     country = text;
                  }
                  else if(name.equals("humidity")){ 	
                     humidity = myParser.getAttributeValue(null,"value");
                  }
                  else if(name.equals("pressure")){
                     pressure = myParser.getAttributeValue(null,"value");
                  }
                  else if(name.equals("temperature")){
                     temperature = myParser.getAttributeValue(null,"value");
                  }
                  else{
                  }
                  break;
                  }		 
                  event = myParser.next(); 

              }
                 parsingComplete = false;
      } catch (Exception e) {
         e.printStackTrace();
      }

   }
   public void fetchXML(){
      Thread thread = new Thread(new Runnable(){
         @Override
         public void run() {
            try {
               URL url = new URL(urlString);
               HttpURLConnection conn = (HttpURLConnection) 
               url.openConnection();
                  conn.setReadTimeout(10000 /* milliseconds */);
                  conn.setConnectTimeout(15000 /* milliseconds */);
                  conn.setRequestMethod("GET");
                  conn.setDoInput(true);
                  conn.connect();
            InputStream stream = conn.getInputStream();

            xmlFactoryObject = XmlPullParserFactory.newInstance();
            XmlPullParser myparser = xmlFactoryObject.newPullParser();

            myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES
            , false);
            myparser.setInput(stream, null);
            parseXMLAndStoreIt(myparser);
            stream.close();
            } catch (Exception e) {
               e.printStackTrace();
            }
        }
    });

    thread.start(); 


   }

}
Following is the modified content of the xml res/layout/activity_main.xml.
<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:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >

   <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="15dp"
      android:text="@string/location"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <EditText
      android:id="@+id/editText1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBottom="@+id/textView1"
      android:layout_alignParentRight="true"
      android:ems="10" />

   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/textView1"
      android:layout_below="@+id/textView1"
      android:layout_marginTop="68dp"
      android:text="@string/country"
      android:textAppearance="?android:attr/textAppearanceSmall" />

   <TextView
      android:id="@+id/textView3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/textView2"
      android:layout_marginTop="19dp"
      android:text="@string/temperature"
      android:textAppearance="?android:attr/textAppearanceSmall" />

   <TextView
      android:id="@+id/textView4"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/textView3"
      android:layout_below="@+id/textView3"
      android:layout_marginTop="32dp"
      android:text="@string/humidity"
      android:textAppearance="?android:attr/textAppearanceSmall" />

   <TextView
      android:id="@+id/textView5"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/textView4"
      android:layout_below="@+id/textView4"
      android:layout_marginTop="21dp"
      android:text="@string/pressure"
      android:textAppearance="?android:attr/textAppearanceSmall" />

   <EditText
      android:id="@+id/editText2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_above="@+id/textView3"
      android:layout_toRightOf="@+id/textView3"
      android:ems="10" >

      <requestFocus />
   </EditText>

   <EditText
      android:id="@+id/editText3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBaseline="@+id/textView3"
      android:layout_alignBottom="@+id/textView3"
      android:layout_alignLeft="@+id/editText2"
      android:ems="10" />

   <EditText
      android:id="@+id/editText4"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_above="@+id/textView5"
      android:layout_alignLeft="@+id/editText1"
      android:ems="10" />

   <EditText
      android:id="@+id/editText5"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBaseline="@+id/textView5"
      android:layout_alignBottom="@+id/textView5"
      android:layout_alignRight="@+id/editText4"
      android:ems="10" />

   <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/editText2"
      android:layout_below="@+id/editText1"
      android:onClick="open"
      android:text="@string/weather" />

</RelativeLayout>
Following is the content of the res/values/string.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">XMLParser</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="location">Location</string>
   <string name="country">Country:</string>
   <string name="temperature">Temperature:</string>
   <string name="humidity">Humidity:</string>
   <string name="pressure">Pressure:</string>
   <string name="weather">Weather</string>
</resources>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.xmlparser"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" />
   <uses-permission android:name="android.permission.INTERNET"/>

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      <activity
         android:name="com.example.xmlparser.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>
   </application>
</manifest>
Let's try to run our XMLParser application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:
Anroid XML Parser Tutorial Now what you need to do is to enter any location in the location field. For example , i have entered London. Press the weather button , when you enter the location. The following screen would appear in you AVD:
Anroid XML Parser Tutorial Now when you press the weather button, the application will contact the Google Weather API and will request for your necessary XML location file and will parse it. In case of London following file would be returned:
Note that this temperature is in kelvin, so if you want to convert it into more understandble format , you have to convert it into Celcius.

Android Camera Tutorial

These are the following two ways , in which you can use camera in your application
  1. Using existing android camera application in our application
  2. Directly using Camera API provided by android in our application

Using existing android camera application in our application

You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera application installed on your phone. Its syntax is given below
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Apart from the above , there are other availaible Intents provided by MediaStore. They are listed as follows
Sr.NoIntent type and description
1ACTION_IMAGE_CAPTURE_SECURE
It returns the image captured from the camera , when the device is secured
2ACTION_VIDEO_CAPTURE
It calls the existing video application in android to capture video
3EXTRA_SCREEN_ORIENTATION
It is used to set the orientation of the screen to vertical or landscape
4EXTRA_FULL_SCREEN
It is used to control the user interface of the ViewImage
5INTENT_ACTION_VIDEO_CAMERA
This intent is used to launch the camea in the video mode
6EXTRA_SIZE_LIMIT
It is used to specify the size limit of video or image capture size
Now you will use the function startActivityForResult() to launch this activity and wait for its result. Its syntax is given below
startActivityForResult(intent,0)
This method has been defined in the activity class. We are calling it from main activity. There are methods defined in the activity class that does the same job , but used when you are not calling from the activity but from somewhere else. They are listed below
Sr.NoActivity function description
1startActivityForResult(Intent intent, int requestCode, Bundle options)
It starts an activity , but can take extra bundle of options with it
2startActivityFromChild(Activity child, Intent intent, int requestCode)
It launch the activity when your activity is child of any other activity
3startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle options)
It work same as above , but it can take extra values in the shape of bundle with it
4startActivityFromFragment(Fragment fragment, Intent intent, int requestCode)
It launches activity from the fragment you are currently inside
5startActivityFromFragment(Fragment fragment, Intent intent, int requestCode, Bundle options)
It not only launches the activity from the fragment , but can take extra values with it
No matter which function you used to launch the activity , they all return the result. The result can be obtained by overriding the function onActivityResult.

Example

Here is an example that shows how to launch the exisitng camera application to capture an image and display the result in the form of bitmap
To experiment with this example , you need to run this on an actual device on which camera is supported.
StepsDescription
1You will use Eclipse IDE to create an Android application and name it as Camera under a package com.example.camera. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add intent code to launch the activity and result method to recieve the output.
3Modify layout XML file res/layout/activity_main.xml add any GUI component if required. Here we add only imageView and a textView.
4Modify res/values/strings.xml to define required constant values
5Run the application and choose a running android device and install the application on it and verify the results.
Following is the content of the modified main activity file src/com.example.camera/MainActivity.java.
package com.example.camera;


import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

public class MainActivity extends Activity {

ImageView imgFavorite;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      imgFavorite = (ImageView)findViewById(R.id.imageView1);
      imgFavorite.setOnClickListener(new OnClickListener() {
         @Override
         public void onClick(View v) {
            open();
         }
      });
   }
   public void open(){
      Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
      startActivityForResult(intent, 0);
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      // TODO Auto-generated method stub
      super.onActivityResult(requestCode, resultCode, data);
      Bitmap bp = (Bitmap) data.getExtras().get("data");
      imgFavorite.setImageBitmap(bp);
   }
   @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;
   }
}
Following will be the content of res/layout/activity_main.xml file:

<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:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity"> 

   <ImageView
   android:id="@+id/imageView1"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_marginLeft="34dp"
   android:layout_marginTop="36dp"
   android:contentDescription="@string/hello_world"
   android:src="@drawable/ic_launcher" />

   <TextView
   android:id="@+id/textView1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentTop="true"
   android:layout_alignRight="@+id/imageView1"
   android:text="@string/tap"
   android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>
Following will be the content of res/values/strings.xml to define one new constants
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">Camera</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="tap">Tap the image to open the camera!!</string>
</resources>
Following is the default content of AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.camera"
   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.example.camera.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>
   </application>

</manifest>
Let's try to run your Camera application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.
Anroid Camera Tutorial Select your mobile device as an option and then check your mobile device which will display following screen:
Anroid Camera Tutorial Now just tap on the image of android icon and the camera will be opened. Just capture a picture. After capturing it , two buttons will appear asking you to discard it or keep it
Anroid Camera Tutorial Just press the tic (green) button and you will be brought back to your application with the captured image inplace of android icon
Anroid Camera Tutorial

Directly using Camera API provided by android in our application

We will be using the camera API to integrate the camera in our application
First you will need to intialize the camera object using the static method provide by the api called Camera.open. Its syntax is
Camera object = null;
object = Camera.open(); 
Apart from the above function , there are other functions provided by the Camera class that which are listed below
Sr.NoMethod & Description
1getCameraInfo(int cameraId, Camera.CameraInfo cameraInfo)
It returns the information about a particular camera
2getNumberOfCameras()
It returns an integer number defining of cameras availaible on device
3lock()
It is used to lock the camera , so no other application can access it
4release()
It is used to release the lock on camera , so other applications can access it
5open(int cameraId)
It is used to open particular camera when multiple cameras are supported
6enableShutterSound(boolean enabled)
It is used to enable/disable default shutter sound of image capture
Now you need make an seperate class and extend it with SurfaceView and implements SurfaceHolder interface.
The two classes that have been used have the following purpose
ClassDescription
CameraIt is used to control the camera and take images or capture video from the camera
SurfaceViewThis class is used to present a live camera preview to the user.
You have to call the preview method of the camera class to start the preview of the camera to the user
public class ShowCamera extends SurfaceView implements SurfaceHolder.Callback {
   
   private Camera theCamera;

   public void surfaceCreated(SurfaceHolder holder) {
      theCamera.setPreviewDisplay(holder);
      theCamera.startPreview();
   }
   public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3){
   }
   public void surfaceDestroyed(SurfaceHolder arg0) {
   }
}	
Apart from the preview there are other options of the camera that can be set using the other functions provided by the Camera API
Sr.NoMethod & Description
1startFaceDetection()
This function starts the face detection in the camera
2stopFaceDetection()
It is used to stop the face detection which is enabled by the above function
3startSmoothZoom(int value)
It takes an integer value and zoom the camera very smoothly to that value
4stopSmoothZoom()
It is used to stop the zoom of the camera
5stopPreview()
It is used to stop the preiview of the camera to the user
6takePicture(Camera.ShutterCallback shutter, Camera.PictureCallback raw, Camera.PictureCallback jpeg)
It is used to enable/disable default shutter sound of image capture

Example

Following example demonstrates the usage of the camera API in the application
To experiment with this example, you will need actual Mobile device equipped with latest Android OS, beacuse camera is not supported by the emulator
StepsDescription
1You will use Eclipse IDE to create an Android application and name it as Camera under a package com.example.camera1. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add the respective code of camera and get references to the XML components.
3Create a new ShowCamera.java file to extend it with SurfaceView and implement the SurfaceHolder interface .
4Modify layout XML file res/layout/activity_main.xml add any GUI component if required. Here we add only FrameView and a button and a ImageView.
5Modify res/values/strings.xml to define required constant values
6Modify AndroidManifest.xml as shown below to add the necessary permissions for camera
7Run the application and choose a running android device and install the application on it and verify the results.
Following is the content of the modified main activity file src/com.example.camera1/MainActivity.java.
package com.example.camera1;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

   private Camera cameraObject;
   private ShowCamera showCamera;
   private ImageView pic;
   public static Camera isCameraAvailiable(){
      Camera object = null;
      try {
         object = Camera.open(); 
      }
      catch (Exception e){
      }
      return object; 
   }

   private PictureCallback capturedIt = new PictureCallback() {

      @Override
      public void onPictureTaken(byte[] data, Camera camera) {

      Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
      if(bitmap==null){
         Toast.makeText(getApplicationContext(), "not taken", Toast.LENGTH_SHORT).show();
      }
      else
      {
         Toast.makeText(getApplicationContext(), "taken", Toast.LENGTH_SHORT).show();    	
      }
      cameraObject.release();
   }
};

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      pic = (ImageView)findViewById(R.id.imageView1);
      cameraObject = isCameraAvailiable();
      showCamera = new ShowCamera(this, cameraObject);
      FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
      preview.addView(showCamera);
   }
   public void snapIt(View view){
      cameraObject.takePicture(null, null, capturedIt);
   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }
}
Create the new java file called assrc/com.example.camera1/ShowCamera.java. and add the following code
package com.example.camera1;

import java.io.IOException;

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

public class ShowCamera extends SurfaceView implements SurfaceHolder.Callback {

   private SurfaceHolder holdMe;
   private Camera theCamera;

   public ShowCamera(Context context,Camera camera) {
      super(context);
      theCamera = camera;
      holdMe = getHolder();
      holdMe.addCallback(this);
   }

   @Override
   public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
   }

   @Override
   public void surfaceCreated(SurfaceHolder holder) {
      try   {
         theCamera.setPreviewDisplay(holder);
         theCamera.startPreview(); 
      } catch (IOException e) {
      }
   }

   @Override
   public void surfaceDestroyed(SurfaceHolder arg0) {
   }

}
Modify the content of the res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="horizontal" >

   <LinearLayout
      android:layout_width="wrap_content"
      android:layout_height="match_parent"
      android:layout_weight="0.30"
      android:orientation="vertical" >
        
         <FrameLayout
            android:id="@+id/camera_preview"
            android:layout_width="fill_parent"
            android:layout_height="199dp" />

         <Button
            android:id="@+id/button_capture"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="snapIt"
            android:text="@string/Capture" />

         <ImageView
            android:id="@+id/imageView1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scaleType="fitXY"
            android:src="@drawable/ic_launcher" />
	  
   </LinearLayout>

< /LinearLayout>
Modify the content of the res/values/string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">Camera1</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="Capture">Capture</string>
    
</resources>
Modify the content of the AndroidManifest.xml and add the necessary permissions as shown below.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.camera1"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" />
   <uses-permission android:name="android.permission.CAMERA"/>
   <uses-feature android:name="android.hardware.camera" />
   <uses-feature android:name="android.hardware.camera.autofocus" />

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
         <activity
            android:name="com.example.camera1.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>
   </application>

</manifest>
Let's try to run your SendSMSDemo application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.
Anroid Camera Tutorial Select your mobile device as an option and then check your mobile device which will display following screen:
Anroid Camera Tutorial The camera would start showing its preview in the upper half panel. Just click the capture button. You can now either store the captured image , upload it to the web or either discard it.