How send boardcasts form service to widget in Android?

39 Views Asked by At

I've implemented a service in my Android app that sends a broadcast every second using a Runnable. The broadcast contains a message with an extra value. Here's the snippet from the service:

Intent intent = new Intent("***.MY_MSG");
intent.putExtra("MY_VAL", favNum);

I successfully receive and handle this broadcast in MainActivity using a BroadcastReceiver. However, I'm facing issues when trying to receive the same broadcast in "MyWidget". Here's the relevant code from my widget provider:

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

    switch (intent.getAction()) {
        case MY_MSG:
            Log.d("devLog", "on widget get broadcast");
            break;

   }

Despite the above implementation, the onReceive method in my AppWidgetProvider doesn't seem to catch the broadcast. Here's what I've checked so far: typos & manifest,

 <receiver android:name=".MyWidget"
            android:exported="true">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                <action android:name="***.MY_MSG" />
            </intent-filter>
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/my_widget_info" />
</receiver>
1

There are 1 best solutions below

0
Jane Jacek On

Good news!!! The main man from the team I'm a part of has figured it out. Sending broadcasts to the widget can be done through a specific intent declaration.

  1. Here is sending broadcast from service to a activity
 Intent intent = new Intent("country.comapnyname.appname.VAL_UPDATE");
 intent.putExtra("my_val", value);
 sendBroadcast(intent);

  1. And here is sending broadcast to the widget
Intent widgetTimeUpdate = new Intent(getApplicationContext(),YourWidget.class);
widgetValUpdate.setAction(YourWidget.VAL_UPDATE);
widgetValUpdate.putExtra("my_val", val);