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

发布于 2025-01-07 17:29:43 字数 88 浏览 0 评论 0原文

我有一个活动。它包含一个按钮,其文本会动态变化。我想将此文本传递给接收短信的广播接收器。现在我的广播接收器应该接收文本,并根据文本启动或停止服务。如何做到这一点?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦晓ヶ微光ヅ倾城 2025-01-14 17:29:43

如果您的 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>

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>
远山浅 2025-01-14 17:29:43

您可以让您的活动向接收器发送意图,并将文本作为额外的内容传递

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

,然后在接收器中,使用 startService 函数

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文