DurgaPrasad Ganti
DurgaPrasad Ganti

Reputation: 1008

How to pass value from activity to broadcastreceiver?

I am developing one application using broadcastreceiver i have problem with receive value in broadcast receiver from activity,please tell me how to send value from activity to broadcast receiver and how to receive value in broadcast receiver from activity ,i am trying like below code but its not working

my code in activity side

Intent intent = new Intent("my.action.string");
    //intent.setAction("IncomCallBroadCast");
    intent.putExtra("contact",phNo);
    sendBroadcast(intent);

in broadcastreceiver side

 String action = intent.getAction();
    Log.i("Receiver", "Broadcast received: " + action);
    if(action.equals("my.action.string")){
        contact = intent.getExtras().getString("contact");
        Log.e("",contact );
    }
manifest
<action android:name="my.action.string"/> 

Upvotes: 0

Views: 1187

Answers (4)

Shailendra Madda
Shailendra Madda

Reputation: 21531

change this line

String action = intent.getAction();
contact = intent.getExtras().getString("contact");

to

Intent intent = getIntent();
contact = intent.getStringExtra("contact");

Upvotes: 1

user957654
user957654

Reputation:

try the following :

Log.e("i am printing my cotnact " , contact );

and give me some feedback

Hope that Helps .

Upvotes: 0

Arunkumar
Arunkumar

Reputation: 3841

Make sure the phNo is of type String. If not, use getInt() in your BroadcastReciever.

You might want to add a String in extras, and retrieve back in String. If the type of phNo variable is int, then you should retrieve the extra value in the form of int only.

Upvotes: 0

Radheshyam Singh
Radheshyam Singh

Reputation: 479

In main activity use this code to start broadcast receiver

Intent intent = new Intent("package.action.string");
intent.putExtra("extra", phoneNo); \\ phoneNo is the sent Number
sendBroadcast(intent);

In the broadcast reciver use this code

public void onReceive(Context context, Intent intent) {
 String action = intent.getAction();

 Log.i("Receiver", "Broadcast received: " + action);

 if(action.equals("package.action.string")){
   String state = intent.getExtras().getString("extra");

  }
}

NOTE : Donot forget to declare your Broadcast receiver in manifest file

<receiver android:name=".SmsReceiver" android:enabled="true">
<intent-filter>
    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    <action android:name="package.action.string" />
    <!-- and some more actions if you want -->
</intent-filter>
</receiver>

Upvotes: 2

Related Questions