从活动传递值的BroadcastReceiver并开始从所述广播接收机的服务 [英] Pass a value from activity to broadcastreceiver and start a service from the broadcast receiver

查看:121
本文介绍了从活动传递值的BroadcastReceiver并开始从所述广播接收机的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动。它包含的文本是动态变化的一个按钮。我想这样的文字传递给我的广播接收器接收短信。现在我的广播接收器应当接收文本和基于文本应开始或停止服务。如何做到这一点?

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?

推荐答案

如果您的BroadcastReceiver是在一个单独的类文件中定义的,那么你可以简单地播放值的接收器。一旦收到的价值,通过接收器的情况下做的魔法服务

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

更新:

在您的活动:

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>

这篇关于从活动传递值的BroadcastReceiver并开始从所述广播接收机的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆