Pages

Subscribe:

Labels

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;
    @Override
    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(PhoneNumberUtils.compare(number1, number)||(number.endsWith(number1))){
                                   Intent intent1=new Intent(context,AudioHandler.class);
                                   intent1.putExtra("filename", details.getFilename());
                                    intent1.putExtra("from",details.getFrom());
                                    intent1.putExtra("subject", details.getSubject());
                                    intent1.putExtra("content", details.getContent());
                                    intent1.putExtra("time", details.getTime());
                                    context.startService(intent1);
                                   
                               }
                        }
                    }
             }
    }




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:

siva said...

Good Post! Thank you so much for sharing this pretty post,
it was so good to read and useful to improve my knowledge as updated one, keep blogging.
Java training in Chennai

Java training in Bangalore

Java online training

Java training in Pune



Post a Comment