activity/service 和小部件提供商之间的通信?

Communication between activity/service and widget provider?

我的应用程序有一个小部件,当用户单击小部件上的按钮时它有 4 个按钮,我必须向连接的蓝牙发送一些代码。在我的蓝牙服务 class 中,我正在传递蓝牙 Mac 地址以连接外部蓝牙设备。 我如何在 android 中的 activity 的服务和小部件或小部件之间进行通信。 如果我使用 getService,我的蓝牙将断开连接。 有什么方法可以在 appWidgetProvider class

中调用服务方法或 activity 方法

您可以在 appWidgetProvider 中做的最好的事情是通过意图向您的 service/activity 发送消息。您可以使用支持库 v4 中的 LocalBroadcastManager 仅在您的应用程序内部广播消息。 示例:

@Override
public void onCreate(Bundle savedInstanceState) {

  ...

  // Register to receive messages.
  // We are registering an observer (mMessageReceiver) to receive Intents
  // with actions named "custom-event-name".
  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
      new IntentFilter("custom-event-name"));
}

// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    // Get extra data included in the Intent
    String message = intent.getStringExtra("message");
    Log.d("receiver", "Got message: " + message);
  }
};

@Override
protected void onDestroy() {
  // Unregister since the activity is about to be closed.
  LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
  super.onDestroy();
}

并且在您的小部件提供商中:

private void sendMessage() {
  Log.d("sender", "Broadcasting message");
  Intent intent = new Intent("custom-event-name");
  // You can also include some extra data.
  intent.putExtra("message", "This is my message!");
  LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}