将值从活动传递到broadcastreceiver并从广播接收器启动服务

时间:2012-02-22 06:45:50

标签: android service android-activity broadcastreceiver

我有一项活动。它包含一个动态更改文本的按钮。我想将此文本传递给接收短信的广播接收器。现在我的广播接收器应该接收文本,并根据文本它应该启动或停止服务。怎么做?

2 个答案:

答案 0 :(得分:5)

如果您的BroadcastReceiver是在单独的类文件中定义的,那么您可以简单地将该值广播到该接收器。收到价值后,使用收件人的context

为服务腾出魔力

<强>更新

在您的活动中:

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

在您的接收器中:

@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
  }
}
清单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>

答案 1 :(得分:1)

您可以让您的活动向接收者发送意图,并将该文本作为额外的

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

然后在您的接收器中,使用startService function

启动服务
相关问题