Wednesday, 28 September 2011

Android BroadcastReceiver for SMS

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class SMSReceiver extends BroadcastReceiver {

    private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
    private SharedPreferences myPrefs;
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "SMS Received", Toast.LENGTH_LONG).show();
        myPrefs = context.getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
            if (intent.getAction().equals(SMS_RECEIVED)) {
                //Toast.makeText(context, "SMS Received", Toast.LENGTH_LONG).show();
                Bundle bundle = intent.getExtras();
                if (bundle != null) {
                    Object[] pdus = (Object[])bundle.get("pdus");
                    final SmsMessage[] messages = new SmsMessage[pdus.length];
                    for (int i = 0; i < pdus.length; i++) {
                        messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                    if (messages.length > -1) {
                        String number=messages[0].getOriginatingAddress();
                          if(, number)||(number.endsWith(number1))){
                                   Intent intent1=new Intent(context,AudioHandler.class);
                                   intent1.putExtra("filename", details.getFilename());
                                    intent1.putExtra("subject", details.getSubject());
                                    intent1.putExtra("content", details.getContent());
                                    intent1.putExtra("time", details.getTime());

And also declare  the bellow permission in the android manifestfile

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

1 comment:

Petter Marry said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training in India . Nowadays Java has tons of job opportunities on various vertical industry.

Post a Comment