What I am trying to do is that the numbers to which my application sends messages to, are passed to the BraodcastReceiver...but so far either I am getting null or BroadcastR
You starting an Activity
instead of broadcasting Intent
.
Try to change
startActivity(intent);
to
sendBroadcast(intent);
UPDATE:
You set no action and no component name to the Intent
.
Try create intent as following:
Intent intent = new Intent(context, YourReceiver.class);
intent.putExtra("phN", phoneNo);
sendBroadcast(intent);
You would send a broadcast like so:
Intent intent = new Intent(action);
intent.putExtra("phN", phoneNo);
sendBroadcast(intent);
The action
parameter is a String
that correlates to the action you registered the BroadcastReceiver
with. So if you registered your receiver like so:
MyBroadcastReceiver receiver = new MyBroadcastReceiver();
registerReceiver( receiver, new IntentFilter( "com.myapp.myaction" ) );
then action
would be "com.myapp.myaction"
use sendbroadcast instead of startactivity.it will work..!!
Following @Jason 's example...I did this...
In MainActivity or any activity from where you want to send intent from
Intent intent = new Intent("my.action.string");
intent.putExtra("extra", phoneNo); \\ phoneNo is the sent Number
sendBroadcast(intent);
and then in my SmsReceiver Class I did this
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i("Receiver", "Broadcast received: " + action);
if(action.equals("my.action.string")){
String state = intent.getExtras().getString("extra");
}
}
And in manifest.xml I added "my.action.string"
though it was an option..
<receiver android:name=".SmsReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
<action android:name="my.action.string" />
<!-- and some more actions if you want -->
</intent-filter>
</receiver>
worked like charm!!
Your problem is actually very simple. It's enough that change onReceive() code just like it :
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i("Receiver", "Broadcast received: " + action);
if(action.equals("my.action.string")){
String state = bundle.getString("phN");
}
}