How to pass value from activity to broadcastreceiver?

China☆狼群 提交于 2019-12-12 01:08:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!