Parsing XML File stored in raw folder using XPath

Following code demonstrates how to parse XML file stored in res/raw folder using XPath

Save following file in res – raw folder as data.xml

<?xml version="1.0" encoding="UTF-8"?>
<sample>
    <info>
        <title>Using XPath to parse XML</title>
        <author>Pete Houston</author>
    <list>
        <person id="1">
            <name>abc</name>
            <age>22</age>
        </person>
 
        <person id="2">
            <name>def</name>
            <age>27</age>
        </person>
 
        <person id="3">
            <name>ghi</name>
            <age>22</age>
        </person>
    </list>
    </info>
</sample>

XMLParse.java

package com.example.xmlparsing;

import java.util.ArrayList;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class MainActivity extends ListActivity {

	ArrayList<String> mPeople = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            parseData();
        } catch(Exception ex) {
            Toast.makeText(this, "Exception: " + ex.getMessage(), Toast.LENGTH_LONG).show();
        }
 
        // pass adapter w/ data queried through XPath to ListView
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mPeople);
        setListAdapter(adapter);
    }
    private void parseData() throws Exception {
        // create an InputSource object from /res/raw
        InputSource inputSrc = new InputSource(getResources().openRawResource(R.raw.data));
        // query XPath instance, this is the parser
        XPath xpath = XPathFactory.newInstance().newXPath();
        // specify the xpath expression
        String expression = "//name";
        // list of nodes queried
        NodeList nodes = (NodeList)xpath.evaluate(expression, inputSrc, XPathConstants.NODESET);
 
        //Toast.makeText(this, "count: " + String.valueOf(nodes.getLength()),Toast.LENGTH_SHORT).show();
        // if node found
        if(nodes != null && nodes.getLength() > 0) {
            mPeople.clear();
            int len = nodes.getLength();
            for(int i = 0; i < len; ++i) {
                // query value
                Node node = nodes.item(i);
                mPeople.add(node.getTextContent());
            }
        }
    }
    
}

XMLParsing1

Advertisements

Testing Network ( Wifi and Mobile) Connection

Following code tests whether network is available and/or connected?

package com.example.networkapidemo5b;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		try
		{
			ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			String s = "Available : " + ni.isAvailable() + "Connected : " + ni.isConnected();
			Toast.makeText(getApplicationContext(), s, 100).show();

                        ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			s = "Available : " + ni.isAvailable() + "Connected : " + ni.isConnected();
			Toast.makeText(getApplicationContext(), s, 100).show();

		}	
		catch(Exception e)
		{
			Toast.makeText(getApplicationContext(), e.getMessage(), 50).show();
		}
	}

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

}

File Read – Write Example

Following Code demonstrates how to read data from file and write data to file.

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"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="68dp"
        android:layout_marginTop="40dp"
        android:ems="10"
        android:inputType="textMultiLine" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="45dp"
        android:text="Button" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_centerVertical="true"
        android:text="Button" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/button2"
        android:layout_below="@+id/button2"
        android:layout_marginTop="58dp"
        android:text="TextView" />

</RelativeLayout>

FileReadWrite.java

package com.example.filereadwrite5a;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

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

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button bwrite = (Button)findViewById(R.id.button1);
		Button bread = (Button)findViewById(R.id.button2);
		final EditText ed = (EditText)findViewById(R.id.editText1);
		final TextView tv = (TextView)findViewById(R.id.textView1);
//		
//		
		bwrite.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				File f = getCacheDir();
				File newfile = new File(f,"mca5.abc");
				try
				{
				newfile.createNewFile();
				//newfile.
				FileOutputStream fos = new FileOutputStream(newfile.getAbsolutePath());
				fos.write(ed.getText().toString().getBytes());
				fos.close();
				}
				catch(Exception e)
				{}
//				File f = getFilesDir();
//				String filelist[] = f.list();
//				String s;
//				for (int i=0;i<filelist.length;i++)
//				{
//					Toast.makeText(getApplicationContext(),filelist[i], 50).show();
//				}
//				try 
//				{
//					String s = ed.getText().toString();
//					FileOutputStream fos = openFileOutput("test.txt", MODE_APPEND);
//					fos.write(s.getBytes());
//					fos.close();
//				} 
//				catch (Exception e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
				
			}
		});
		bread.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try 
				{
					FileInputStream fis = openFileInput("mca5a.txt");
					DataInputStream dis = new DataInputStream(fis);
					String s="";
					String s1 = "";
					while ((s=dis.readLine())!=null)
					{
						s1 += s;
					}
					tv.setText(s1.toString());
				} 
				catch (Exception e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		});
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

AsyncTask Class Example

There are two ways to offload main thread’s task
1) Java Thread Class
2) AsyncTask class

Following Code demonstrates how to use AsyncTask class to offload task of main thread.

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"
    tools:context=".MainActivity" >

    <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="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="48dp"
        android:layout_toLeftOf="@+id/textView1"
        android:text="Button" />

</RelativeLayout>

AsyncTaskActivity.java

package com.example.asynctaskactivity;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements View.OnClickListener 
{
	Button btn;
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btn = (Button) findViewById(R.id.button1);
	
		//because we implement OnClickListener we only have to pass "this" (much easier)
		btn.setOnClickListener(this);
	}

	public void onClick(View view)
	{

		switch(view.getId())
		{
			case R.id.button1:
//				for(int i=0;i&lt;5;i++) {
//					try {
//						Thread.sleep(1000);
//					} catch (InterruptedException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//				}
//				TextView txt = (TextView) findViewById(R.id.textView1);
//				txt.setText(&quot;Executed&quot;);
				new LongOperation().execute(&quot;&quot;);
				break;
		}	

	}
	private class LongOperation extends AsyncTask {

		@Override
		protected String doInBackground(String... params) {
			Log.d("xml", "DoinBackground");
			for(int i=0;i&lt;5;i++) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			return &quot;Executed&quot;;
		}      

		@Override
		protected void onPostExecute(String result) 
		{
			Log.d(&quot;xml&quot;, &quot;OnPostExecute&quot;);
			TextView txt = (TextView) findViewById(R.id.textView1);
			txt.setText(&quot;Executed&quot;); // txt.setText(result);
			//might want to change &quot;executed&quot; for the returned string passed into onPostExecute() but that is upto you
		}

		@Override
		protected void onPreExecute() 
		{
			Log.d(&quot;xml&quot;, &quot;OnPreExecute&quot;);
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}
}

Web – API Demo

Following Code Demonstrates How to Display HTML page stored in Asset folder to display in webview
test.html file contains HTML + JavaScript code
test1.html is an example where Android Source code is communicating with Javascript code Stored in Assets folder
and viceversa.

Assets – test.html

<html>
	<title>WEB-API Demo</title>
	<script language="JavaScript">
		function f1()
		{
			alert("hello");
		}
	</script>
	<body>
		<form>
			<input type="button" value="hello" onClick="f1()"/>
		</form>
	</body>
</html>

Assets -> test1.html

<html>
<head>
<script type="text/javascript">
function doAlert() 
{
	alert("This is an alert.");
}
function doToast()
{
	mca5a.testtoast(document.getElementById("form_text").value,50);
}
function doLog()
{
	console.log("this is test log");
}
function doSetHTMLText(update)
{
	document.getElementById("form_text") = update;
}
</script>
</head>
<body>
<h2>This is a test.</h2>
<input type="text" value="data" id="form_text"/>
<input type="button" value="Alert" onclick="doAlert();" />
<input type="button" value="Toast" onclick="doToast();" />
<input type="button" value="Log" onclick="doLog();" />
</body>
</html>

WebAPIDEmo.java

package com.example.webapidemo5a;



import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebSettings.TextSize;
import android.webkit.WebSettings.ZoomDensity;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		final WebView wv = (WebView)findViewById(R.id.wv1);
		//final TextView tv = (TextView)findViewById(R.id.textView1);
		wv.getSettings().setJavaScriptEnabled(true);
		wv.setWebChromeClient(new WebChromeClient());
		wv.addJavascriptInterface(new test(), "mca5a");
//		wv.loadUrl("file:///android_asset/test.html");
		wv.loadUrl("file:///android_asset/test1.html");
		
	}
	public void setHTMLText(View view) 
	{
		WebView wv = (WebView) findViewById(R.id.wv1);
		wv.loadUrl("javascript:doSetHTMLText('Java->JS call');");
	}
	public class test
	{
		public void testtoast(String msg,int duration)
		{
			Toast.makeText(getApplicationContext(), msg, duration).show();
		}
	}

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

}

Making and Receiving Phone Call Application

Following Code Demonstrates How to make phone call from your android app as well as how
to receive phone call (i.e. knowing from which number incoming call is there)

MakeReceivePhoneCall.java

package com.example.makingrecevingphonecall;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

	Button btn;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btn = (Button) findViewById(R.id.button1);
		final EditText et = (EditText)findViewById(R.id.editText1);

		PhoneCallListener phoneCallListener = new PhoneCallListener();
		TelephonyManager telManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
		telManager.listen(phoneCallListener, PhoneStateListener.LISTEN_CALL_STATE);
		et.addTextChangedListener(
				new PhoneNumberFormattingTextWatcher());
		// add button listeners
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				//EditText numberEntry = (EditText) 	findViewById(R.id.number_entry);
				Intent i = new Intent(Intent.ACTION_DIAL);
				i.setData(Uri.parse("tel:123456"));
				startActivity(i);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	// monitor phone call states
		private class PhoneCallListener extends PhoneStateListener {

			String TAG = "LOGGING PHONE CALL";

			private boolean phoneCalling = false;

			@Override
			public void onCallStateChanged(int state, String incomingNumber) {

				if (TelephonyManager.CALL_STATE_RINGING == state) {
					// phone ringing
					Log.i(TAG, "RINGING, number: " + incomingNumber);
				}

				if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
					// active
					Log.i(TAG, "OFFHOOK");

					phoneCalling = true;
				}

				// When the call ends launch the main activity again
				if (TelephonyManager.CALL_STATE_IDLE == state) {

					Log.i(TAG, "IDLE");

					if (phoneCalling) {

						Log.i(TAG, "restart app");

						// restart app
						Intent i = getBaseContext().getPackageManager()
								.getLaunchIntentForPackage(
										getBaseContext().getPackageName());

						i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(i);

						phoneCalling = false;
					}

				}
			}
		}
}

manifest.xml file

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.makingrecevingphonecall.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>

Send and Receive SMS Application from Android

Following code demonstrates how to send and receive SMS using Telephony API in Android

SendSMS.java

package com.example.sendreceivesms;

import java.util.ArrayList;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends Activity {
	private static String SENT = "SMS_SENT";
	private static String DELIVERED = "SMS_DELIVERED";
	private static int MAX_SMS_MESSAGE_LENGTH = 160;
	static Context mContext;
	BroadcastReceiver smsSentReceiver, smsDeliveredReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mContext = getApplicationContext();
		Button b = (Button)findViewById(R.id.button1);
		b.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				// TODO Auto-generated method stub
				sendSMS("5554","HELLO from mca5b");
//				sendSMS("5554", "helloasdfadsklfjadslkfjadsklfjladskjflkadsjflksadjfkldsajflkadsjfkladsjflkadsjflkadsjflkasdjflkadsjflkadsjf" +
//						"SADKFJADSKLFJADSKLJFLADSKJFL;ADSKJFLADSKJFLKADSJFLKADSJFL;ADSKJFLKADS" +
//						"KASLDFJAKLDSJFKLADSJFLKASDJFLKADSJFLKADSJLKFJADSKLFJADSLKFADSJFLKASD" +
//						"LKADSJFLADKSJFDKLASJFL;AKSDJFLKADSJFL;KASDJFLKADSJFLKDSAJFLASDJFAS;DL" +
//						"AKLDSJFLADKSJFLKADSJFKLASDJFKLADSJFKLADSJFLKADJSLKFJASDKLFJASD" +
//						"ADSKLFJADSKLJFKALSDJFLKAJDSLKFJDASLKFJADLSKFJADSLFJASDL;KF" +
//						"adlskfjadlskfjal;dskfjalkdsjfl;kadsjfaldskjfaldskjflkdasjfl");
			}
		});
	}

	// ---sends an SMS message to another device---
	public void sendSMS(String phoneNumber, String message) 
	{
		//PendingIntent.get
		PendingIntent piSent=PendingIntent.getBroadcast(this, 0, new Intent("SMS_SENT"), 0);
		PendingIntent piDelivered=PendingIntent.getBroadcast(this, 0, new Intent("SMS_DELIVERED"), 0);
		//		PendingIntent piSent = PendingIntent.getBroadcast(mContext, 0, new Intent(SENT), 0);
		//	PendingIntent piDel-ivered = PendingIntent.getBroadcast(mContext, 0,new Intent(DELIVERED), 0);
		SmsManager smsManager = SmsManager.getDefault();

		int length = message.length();          
		if(length > MAX_SMS_MESSAGE_LENGTH) {
			ArrayList<String> messagelist = 
					smsManager.divideMessage(message);     
			//	smsManager.sendMultipartTextMessage(phoneNumber, null, messagelist, piSent,piDelivered );
			smsManager.sendMultipartTextMessage(phoneNumber, null, messagelist,null,null); 

		}
		else
		{
			smsManager.sendTextMessage(phoneNumber, null, message, 
					piSent,piDelivered);
		}
	}
	public void onResume() 
	{
		super.onResume();
		smsSentReceiver=new BroadcastReceiver() 
		{
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				// TODO Auto-generated method stub
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					Toast.makeText(getBaseContext(), "SMS has been 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;
				default:
					break;
				}

			}
		};
		smsDeliveredReceiver=new BroadcastReceiver() {

			@Override
			public void onReceive(Context arg0, Intent arg1) {
				// TODO Auto-generated method stub
				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;
				}
			}
		};

		registerReceiver(smsSentReceiver, new IntentFilter("SMS_SENT"));
		registerReceiver(smsDeliveredReceiver, new IntentFilter("SMS_DELIVERED"));
	}

	public void onPause() {
		super.onPause();
		unregisterReceiver(smsSentReceiver);
		unregisterReceiver(smsDeliveredReceiver);
	}

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

}

SMSReciever.java

package com.example.sendreceivesms;

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[]) intent.getExtras().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();
		}                         
	}

}

Manifest file

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.sendreceivesms.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>
        <receiver android:name=".SMSReceiver"> 
            <intent-filter> 
                <action android:name=
                    "android.provider.Telephony.SMS_RECEIVED" /> 
            </intent-filter> 
        </receiver>
 
    </application>

</manifest>