How to pass data to BroadcastReceiver?

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!!


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);