In my Android app I would like to be able to notify an activity when I receive an SMS, and give this activity the number of the sender. To achieve this goal I'm using a BroadcastReceiver class that collects the phone number(s) of SMS senders and send them in a broadcasted intent.
public class SMSReceiver extends BroadcastReceiver {
final public static String SMS_BROADCAST = "myapp.BROADCAST_SMS";
final public static String SMS_BROADCAST_EXTRA = "myapp.GET_SMS";
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras == null)
return;
Object[] pdus = (Object[]) extras.get("pdus");
SmsMessage Sms[] = new SmsMessage[pdus.length];
String numbers[] = new String[pdus.length];
//get the sms's
for (int i = 0; i < pdus.length; i++) {
Sms[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
String sender = Sms[i].getOriginatingAddress();
numbers[i] = sender;
}
//pass the number array to my activity via an intent.
Intent intent2 = new Intent(SMS_BROADCAST);
intent2.putExtra(SMS_BROADCAST_EXTRA, numbers);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent2);
}
}
And here is where I register the receiver in my activity. I receive the intent, but the array of strings "numbers" is always null. If I try to do something with it, I always have a null pointer exception.
@Override
public void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(SMSReceiver.SMS_BROADCAST);
BroadcastReceiver SmsReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(SMSReceiver.SMS_BROADCAST)) {
String numbers[] = getIntent().getStringArrayExtra(SMSReceiver.SMS_BROADCAST_EXTRA);
if (numbers == null) {
// This always appears in the log !!!
Log.d("NUMBERS", "IS NULL");
return;
}
// do something with the numbers
}
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(SmsReceiver, intentFilter);
}
I still can't see what I did wrong, but I'm quite a newbie in Android development. So any help would be greatly appreciated.
You are using Activity
intent with method getIntent()
instead onReceive
intent
change to getIntent()
to intent
String numbers[] = intent.getStringArrayExtra(SMSReceiver.SMS_BROADCAST_EXTRA);