活动/服务和小部件提供商之间的通信?

时间:2018-04-30 11:17:18

标签: android android-widget android-pendingintent android-appwidget

我的应用程序有一个小部件,当用户单击小部件上的按钮时,它有4个按钮我必须向连接的蓝牙发送一些代码。在我的蓝牙服务类中,我通过蓝牙Mac地址连接外部蓝牙设备。 如何在服务和小部件或小部件之间与android中的活动进行通信。 如果我使用getService,我的蓝牙会断开连接。 有没有办法在appWidgetProvider类中调用服务方法或活动方法

1 个答案:

答案 0 :(得分:3)

你可以在appWidgetProvider中做的最好的事情是通过意图向你的服务/活动发送消息。您可以使用支持库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);
}