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

xyz*_*oid 2 service android broadcastreceiver android-activity

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

waq*_*lam 5

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

更新:

在你的活动中:

Intent in = new Intent("my.action.string");
in.putExtra("state", "activated");
sendBroadcast(in);
Run Code Online (Sandbox Code Playgroud)

在你的接收器:

@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
  }
}
Run Code Online (Sandbox Code Playgroud)

在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>
Run Code Online (Sandbox Code Playgroud)