Ravs
Ravs

Reputation: 261

Android app widget update based on contentprovider data change

I am trying to add a widget to the launcher3 app that takes data from a contentprovider running in a separate process and displays it in a listview in the widget. The widget must update its listview items whenever the contentprovider data gets changed. I am looking for a few samples to understand how this works.Can someone point me to some links or samples for this?

Upvotes: 1

Views: 1170

Answers (1)

Karakuri
Karakuri

Reputation: 38605

You have to manually trigger an update. One way to do this is to send a broadcast intent to your AppWidgetProvider.

public class MyAppWidgetProvider extends AppWidgetProvider {
    private static final String REFRESH_ACTION = "com.mypackage.appwidget.action.REFRESH";

    public static void sendRefreshBroadcast(Context context) {
        Intent intent = new Intent(REFRESH_ACTION);
        intent.setComponent(new ComponentName(context, MyAppWidgetProvider.class));
        context.sendBroadcast(intent);
    }

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

        if (REFRESH_ACTION.equals(action)) {
            // refresh all your widgets
            AppWidgetManager mgr = AppWidgetManager.getInstance(context);
            ComponentName cn = new ComponentName(context, ScheduleWidgetProvider.class);
            mgr.notifyAppWidgetViewDataChanged(mgr.getAppWidgetIds(cn), R.id.widget_list);
        }
        super.onReceive(context, intent);
    }

    ...
}

When data that is displayed by your app widget changes, your ContentProvider can simply call MyAppWidgetProvider.sendRefreshBroadcast(getContext()).

Upvotes: 1

Related Questions