【问题标题】:Android: sending LocalBroadcastManager's intents from BroadcastReceiver eventsAndroid:从 BroadcastReceiver 事件发送 LocalBroadcastManager 的意图
【发布时间】:2014-01-10 04:22:00
【问题描述】:

我遇到了一种奇怪的情况,即从服务或 MainActivity 向 LocalBroadcastManager 注册了一个意图接收器,而当从 PHONE_STATE 接收器(在 AndroidManifest.xml 中定义)发送意图时,它从未被接收到。

从活动|服务发送相同意图的“自我测试” - 有效。

是否值得尝试指定通过 AndroidManifest.xml 接收 LocalBroadcastManager 的意图?


服务定义为:

    <service
     android:name=".AppService"
     android:process=":remote">
      <intent-filter>
       <action android:name="me.cmp.app.AppService" />
      </intent-filter>
    </service>

在役:

 public class AppService extends Service {
 @Override
 public void onCreate() {
        super.onCreate();
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("me.cmp.app.statechange"));

            // self-test uses same intent sending code:
            Intent intent2 = new Intent("me.cmp.app.statechange");
            intent2.putExtra("message", "selfsend");
            LocalBroadcastManager.getInstance(this).sendBroadcastSync(intent2);

 }  
 ...

在清单中:

    <receiver android:name="me.cmp.app.PhoneReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE" >
            </action>
        </intent-filter>
    </receiver>        

听众:

public class PhoneReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
    Bundle extras = intent.getExtras();
    if (extras != null) {
      Log.e("test", extras.getString(TelephonyManager.EXTRA_STATE));

      Intent intent2 = new Intent("me.cmp.app.statechange");
      intent2.putExtra("message", state.toString());
      LocalBroadcastManager.getInstance(context).sendBroadcastSync(intent2);
      Log.w("test", "Broadcast sent");
    }
  }
}

--

主要问题似乎是 Should I use android: process =":remote" in my receiver?但是我仍然不确定为什么 MainActivity 的接收器没有更早地工作,也许完全限定名称是必须的

【问题讨论】:

  • 发布每次广播发送的代码。
  • 当前代码不起作用(因此,完全限定的意图名称或 sendBroadcastSync 都没有太大帮助。
  • 我看到的差异是您的服务是App,而清单有AppService。我会确保该服务正在运行,但我会拿出 android:process=":remote" 看看它是否有任何作用。
  • @A--c App/Appservice 是一个错字;删除 android:process=":remote" 有效,你能把它作为答案吗?
  • 我看到了你的编辑,MainActivity's receiver didn't worked earlier? 是什么意思如果服务是唯一的 remote,那么LocalBroadcasts 将无法按预期工作是有道理的跨度>

标签: android android-intent android-context


【解决方案1】:

LocalBroadcastReceiver 文档声明它是一个

帮助注册并向本地对象发送 Intent 广播 在您的流程中

这意味着如果您正在使用在单独进程中运行的服务(例如android:process=":remote"),LocalBroadcastManager 很可能会失败(尽管是静默),因为您可能会获得此类的两个单独实例(一个每个进程)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多