问题
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"/>
回答1:
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>
回答2:
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.
回答3:
try the following :
Log.e("i am printing my cotnact " , contact );
and give me some feedback
Hope that Helps .
回答4:
change this line
String action = intent.getAction();
contact = intent.getExtras().getString("contact");
to
Intent intent = getIntent();
contact = intent.getStringExtra("contact");
来源:https://stackoverflow.com/questions/21422656/how-to-pass-value-from-activity-to-broadcastreceiver