Search code examples
androidandroid-widgetandroid-pendingintentandroid-appwidget

Communication between activity/service and widget provider?


My app has one widget it has 4 buttons when the user clicks buttons on widget I have to send some code to the connected Bluetooth. In my Bluetooth service class I am passing Bluetooth Mac address to connect with external Bluetooth devices. How can I communicate between service and widget or widget to activity in android. If I use getService my Bluetooth would disconnect. Is there any way to call service methods or activity methods in appWidgetProvider class


Solution

  • The best thing you can do in appWidgetProvider is to send messages to your service/activity via intents. You can use the LocalBroadcastManager in support library v4 to broadcast messages internally to your app only. Example:

    @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();
    }
    

    And in your widget provider:

    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);
    }