0

我一直在尝试使用 LocalBroadcastManager,但它似乎不起作用。基本上我希望我的 intentService 在运行时广播一个意图。然后,我希望我的活动在用户积极使用活动时接收广播。

我尝试按照此处的说明进行操作: 如何使用 LocalBroadcastManager?

但由于某种原因它不起作用。我没有得到任何被调用的接收者的日志条目。

这是我的代码的相关部分:

public class MainActivity extends Activity {
  // Debug log tag
  private static final String tag = "PhoneControlMainActivity";

  // Broadcast receiver
  PhoneControlBroadcastReceiver receiver;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // Register the receiver with the local broadcast manager
    receiver = new PhoneControlBroadcastReceiver();
    LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter(PhoneControlBroadcastReceiver.SERVICE_OUTPUT));

    // Start IntentService
    try {
      serviceName = startService(new Intent(this, PhoneControlIntentService.class));
    }
    catch(SecurityException e)
    {
      Log.d(tag,"SecurityException occured when starting IntentService: "+ e.getMessage());
      return;
    }

    if(serviceName != null) {
      Log.d(tag,"serviceName NOT NULL");
    }
    else {
      Log.d(tag,"serviceName NULL");
    }
  }
}

public class PhoneControlIntentService extends IntentService  {
  public PhoneControlIntentService() {
    super("PhoneControlIntentService");
  }

  @Override
  protected void onHandleIntent(Intent intent) {    
    Intent msgIntent = new Intent(PhoneControlBroadcastReceiver.SERVICE_OUTPUT);
    msgIntent.putExtra("message", "This is my message!");
    LocalBroadcastManager.getInstance(this).sendBroadcast(msgIntent);
  }
}

public class PhoneControlBroadcastReceiver extends BroadcastReceiver{   
  // Action
  public static final String SERVICE_OUTPUT = "com.axr0284.phonecontrol.SERVICE_OUTPUT";

  @Override
  public void onReceive(Context context, Intent intent) {
    Log.d(tag,"onReceive called");      
  }
}

任何帮助将不胜感激?谢谢阿米什

4

2 回答 2

3

LocalBroadcastManager 不能在它自己的进程之外广播。

于 2013-09-01T12:11:36.740 回答
0

这是我做错了什么,我serviceAndroidManifest.xml这行中的声明

android:process=":PhoneControlIntentService_process"

<service
    android:name=".PhoneControlIntentService" 
    android:label="@string/IntentService_name"
    android:process=":PhoneControlIntentService_process"**
    android:exported="false"/>

这应该service作为一个单独的进程启动。我想它以某种方式阻止了正确localBroadcastManager发送intent。我不太明白,但是当我删除那条线时,它开始工作了。

于 2012-12-29T18:41:04.567 回答