AppWidgetManager.getAppWidgetIds in activity returns an empty list

前端 未结 3 538
感动是毒
感动是毒 2021-02-06 08:34

I have an appwidget that I\'m trying to update from an activity.

To do that, I need the appwidget id.

I\'ve used AppWidgetManager.getAppWidgetIds bu

3条回答
  •  太阳男子
    2021-02-06 09:12

    I'm working on something similar and here is the simplest way I got it to work.

    In your service class put this wherever you want to trigger a widget update:

    Intent brIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
    sendBroadcast(brIntent);
    

    This will cause the onReceive(Context context, Intent intent) method in your AppWidgetProvider class to be called. Then onRecieve can call code to update the widget. For a sample, here's what I used. I'm merely updating the text of the widget:

            //Sample output text
        String text = "My cat's name is wiggles.";
        //get an AppWidgetManager
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        //getComponentName
        ComponentName thisWidget = new ComponentName(context, MyWidgetProvider.class);
        //get the IDs for all the instances of this widget
        int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
        //update all of the widgets
        for (int widgetId : allWidgetIds) {
            //get any views in this instance of the widget
            RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
            // Set the text
            remoteViews.setTextViewText(R.id.widgetField,  text);
            //update the widget with any change we just made
            appWidgetManager.updateAppWidget(widgetId, remoteViews);
        }
    

提交回复
热议问题