无法接收来自服务的广播

时间:2015-02-26 14:37:45

标签: java android android-intent service broadcastreceiver

我遇到的问题是从Android库项目中的服务接收广播。

为什么我无法接收广播?是否与单独的android库项目中的所有服务/接口逻辑有关?

这是来自服务的广播

    broadcastReceivedMessage("THE TOPIC", "THE MESSAGE");

这是服务中的方法

    private void broadcastReceivedMessage(final String topic, final String message) {
/*      handler.post(new Runnable() {
            @Override
            public void run() {*/
                Intent broadcastIntent = new Intent(CALLBACK_ACTION);
                broadcastIntent.setAction(ON_MESSAGE_RECEIVED);
                broadcastIntent.putExtra(TOPIC_STR, topic);
                broadcastIntent.putExtra(MESSAGE_STR, message);
                sendBroadcast(broadcastIntent);
/*          }
        });*/

    }

在实现许多接口的类中,我正在注册以侦听特定的intent过滤器。

  @Override
  public void connect(String address, int port) {
    IntentFilter filter = new IntentFilter(MQTTService2.CALLBACK_ACTION);
    LocalBroadcastManager.getInstance(getContext()).registerReceiver(serviceActionReceiver, filter);
    Bundle args = new Bundle();
    args.putString(MQTTService2.BROKER_ADDR_STR, address);
    args.putInt(MQTTService2.BROKER_PORT_INT, port);
    startService(MQTTService2.ACTION_CONNECT, args);
  }

在一个Activity里面,我希望从接口接收回调并获得我的广播

  MQTTEventHandler mHandler = new MQTTEventHandler() {

  @Override
  public void onStatusChanged(CommunicatorStatus status, String message) {
    // TODO Auto-generated method stub
    Log.e("onStatusChanged", "----------------Status Changed------------");
    Log.e("STATUS: ", status.toString());
    Log.e("MESSAGE: ", message);
    Log.e("onStatusChanged", "--------------------------------------------");

  }

  @Override
  public void onMessageReceived(String topic, String message) {
    // TODO Auto-generated method stub
    Log.e("onMessageReceived", "----------------Message Received------------");
    Log.e("TOPIC: ", topic);
    Log.e("MESSAGE: ", message);
    Log.e("onMessageReceived", "--------------------------------------------");

  }

  @Override
  public void onException(String message) {
    // TODO Auto-generated method stub

  }
};

mComm.addEventHandler(mHandler);

广播接收器

class ServiceActionReceiver extends BroadcastReceiver {



    @Override
    public void onReceive(Context context, Intent intent) {

      String action = intent.getAction();
      if (action.equals(MQTTService2.ON_EXCEPTION)) {
        Bundle extras = intent.getExtras();
        if (extras != null && extras.containsKey(MQTTService2.MESSAGE_STR))
          fireOnException(extras.getString(MQTTService2.MESSAGE_STR));
      } else if (action.equals(MQTTService2.ON_MESSAGE_RECEIVED)) {
        Bundle extras = intent.getExtras();
        if (extras != null && extras.containsKey(MQTTService2.MESSAGE_STR)
            && extras.containsKey(MQTTService2.TOPIC_STR))
          fireOnMessageReceived(extras.getString(MQTTService2.TOPIC_STR),
              extras.getString(MQTTService2.MESSAGE_STR));

      } else if (action.equals(MQTTService2.ON_STATUS_CHANGED)) {
        Bundle extras = intent.getExtras();
        if (extras.containsKey(MQTTService2.STATUS_CODE)) {
          MQTTService2.MQTTConnectionStatus status =
              MQTTConnectionStatus.parseCode(extras.getString(MQTTService2.STATUS_CODE));
          switch (status) {
            case CONNECTED:
              fireOnStatusChanged(CommunicatorStatus.DISCONNECTED,
                  extras.getString(MQTTService2.MESSAGE_STR, ""));
              break;
            case CONNECTING:
              break;
            case INITIAL:
              break;
            case NOTCONNECTED_DATADISABLED:
            case NOTCONNECTED_UNKNOWNREASON:
            case NOTCONNECTED_USERDISCONNECT:
            case NOTCONNECTED_WAITINGFORINTERNET:
              fireOnStatusChanged(CommunicatorStatus.DISCONNECTED,
                  extras.getString(MQTTService2.MESSAGE_STR, ""));
              break;
            default:
              break;

          }
        }

      }
    }
  }

根据特定的意图过滤器调用的方法(onMessageReceived)

      private void fireOnMessageReceived(String topic, String message) {
    for (MQTTEventHandler eventHandler : handlers) {
      eventHandler.onMessageReceived(topic, message);
    }
/*    for (Iterator<MQTTEventHandler> it = handlers.iterator(); it.hasNext();) {
      it.next().onMessageReceived(topic, message);
    }*/
  }

1 个答案:

答案 0 :(得分:1)

以下情况似乎导致从您的服务广播的Intent与BroadcastReceiver上设置的IntentFilter不匹配。

Intent broadcastIntent = new Intent(CALLBACK_ACTION);
broadcastIntent.setAction(ON_MESSAGE_RECEIVED);

CALLBACK_ACTION设置IntentFilter,并使用相同的操作实例化Intent,但上面的第二行是将Intent的操作重置为ON_MESSAGE_RECEIVED,导致它不再匹配过滤BroadcastReceiver。

一种可能的解决方案是向IntentFilter添加多个操作,并检查Receiver的onReceive()方法中的传递操作,以确定如何处理广播。

例如:

IntentFilter filter = new IntentFilter(MQTTService2.ACTION_MESSAGE_RECEIVED);
filter.addAction(MQTTService2.ACTION_OTHER);

然后,在onReceive()方法中:

@Override
public void onReceive(Context context, Intent intent)
{
    String action = intent.getAction();

    if(action.equals(ACTION_MESSAGE_RECEIVED)) {
        ...
    }
    else if(action.equals(ACTION_OTHER)) {
        ...
    }
    ...
}

然后,您将使用所需操作实例化广播Intent,然后删除setAction()调用:

Intent broadcastIntent = new Intent(MQTTService2.ACTION_MESSAGE_RECEIVED);
...