Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't update android widget from BroadcastReceiver

I want to code an app that displays some information in an widget, which should be updated from time to time. From time to time means, that I use an alarm timer to trigger a peroidic update. So heres the problem: intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS); is null for the broadcast receivers intent.

Here's my widget provider:

public class MyWidgetProvider extends AppWidgetProvider {
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int N = appWidgetIds.length;      
    for(int i=0; i<N; i++) {
            int widgetId = appWidgetIds[i];         
            RemoteViews rViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);         
            Intent intent = new Intent(context.getApplicationContext(), TrafficService.class);
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);            
            rViews.setTextViewText(R.id.TextView01, "" + System.currentTimeMillis());           
            appWidgetManager.updateAppWidget(widgetId, rViews);
        }
    }
}

and this is the BroadcastReceiver causing the problem:

public class TimeIntervalReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
// set new alarm timer (code cut out)       
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context.getApplicationContext());
        // PROBLEM BELOW!
        int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);     
        if(appWidgetIds == null) Log.d("TRAFFIC", "oh SHIT");
        if(appWidgetIds != null && appWidgetIds.length > 0) {
            for(int widgetId : appWidgetIds) {
                RemoteViews rViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
                rViews.setTextViewText(R.id.TextView01, "some data");
                appWidgetManager.updateAppWidget(widgetId, rViews);
            }
        }
    }
}

Is this even solveable?

like image 995
xenonite Avatar asked Feb 22 '23 06:02

xenonite


1 Answers

Lol, I have my answer...

Simply replace:

int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);

by

ComponentName thisWidget = new ComponentName(getApplicationContext(),MyWidgetProvider.class);
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
like image 174
Waza_Be Avatar answered Mar 05 '23 00:03

Waza_Be