Search code examples
androidbroadcastreceiverdashclock

Dashclock Widget extension not updating


I have a DashClockExtension that sometimes doesn't update.

It's using a LocalBroadcastReceiver to update the extension similar to http://bit.ly/1e4uMl0. The receiver is registered in the onInitialize() method:

@Override
    protected void onInitialize(boolean isReconnect) {
        super.onInitialize(isReconnect);

        LocalBroadcastManager broadcastMgr = LocalBroadcastManager.getInstance(this);
        if (mDashClockReceiver != null) {
            try {
                broadcastMgr.unregisterReceiver(mDashClockReceiver);
            } catch (Exception ignore) {}
        }
        mDashClockReceiver = new DashClockUpdateReceiver();
        broadcastMgr.registerReceiver(mDashClockReceiver, new IntentFilter(UPDATE_DASHCLOCK));
    }

That's how I send the broadcast:

public static void updateDashClock() {
    LocalBroadcastManager.getInstance(Application.getContext()).sendBroadcast(new Intent(UPDATE_DASHCLOCK));
}        

That's my BroadcastReceiver:

private class DashClockUpdateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        retrieveDataAndUpdateWidget();
    }
}

I noticed that while the broadcast is triggered the receiver doesn't receive the event sometimes.
I tested it by killing my app but that doesn't reproduce the issue so I'm at a loss why this would happen.

Anyone?


Solution

  • While my first answer works, it has some undesired side-effects. I therefore came up with a better solution with no side-effects.

    Instruct DashClockWidget to observe a certain Uri using addWatchContentUris and then when it's time to update the widget just call notifyChange on that Uri:

    public class DashClockService extends DashClockExtension {
        private static final Uri URI_BASE = Uri.parse("content://com.myauthority");
        private static final String URI_PATH_SEGMENT = "dashclock/update";
    
        public static void updateWidget(Context context) {
            ContentResolver contentResolver = context.getContentResolver();
            Uri uri = Uri.withAppendedPath(URI_BASE, URI_PATH_SEGMENT);
            contentResolver.notifyChange(uri, null);
        }
    
        @Override
        protected void onInitialize(boolean isReconnect) {
            super.onInitialize(isReconnect);
    
            removeAllWatchContentUris();
            Uri uri = Uri.withAppendedPath(URI_BASE, URI_PATH_SEGMENT);
            addWatchContentUris(new String[] {uri.toString()});
        }
    

    updateWidget can be called from anywhere in the code to update the widget. Most importantly it can be called when the app starts, e.g. after it has been killed by Android and is restarting (I'm calling the update in Application.onCreate()).