Pass a value from activity to broadcastreceiver and start a service from the broadcast receiver

谁说我不能喝 提交于 2019-12-02 05:46:39

问题


I have an activity. It contains a button whose text changes dynamically. I would like to pass this text to my broadcast receiver which receives the sms. Now my broadcast receiver should receive the text and based on the text it should start or stop a service. How to do this?


回答1:


if your BroadcastReceiver is defined in a separate class file, then you may simply broadcast the value to that receiver. Once the value is received, do the magic for service by using receiver's context

Update:

in your activity:

Intent in = new Intent("my.action.string");
in.putExtra("state", "activated");
sendBroadcast(in);

in your receiver:

@Override
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("state");
     //do your stuff
  }
}

in manifest xml:

<receiver android:name=".YourBroadcastReceiver" 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>



回答2:


You can have your activity send an intent to the receiver, and pass the text as an extra

Intent i= new Intent(this, YourReceiver.class);
i.putExtra("txt", "the string value");
startActivity(i)

And then in your receiver, start the service using the startService function



来源:https://stackoverflow.com/questions/9390279/pass-a-value-from-activity-to-broadcastreceiver-and-start-a-service-from-the-bro

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