Android App Widget - 使用哪个上下文

Android App Widget - which context to use

我有一个在接收更新时启动 intentService 的应用小部件。

我不确定要使用哪个上下文来更新 Widget,我应该使用以下之一:

  1. 应用程序上下文
  2. AppWidgetProvider 中收到的上下文
  3. IntentService 上下文

有时我遇到麻烦,更新Widget指令(通过RemoteViews)被忽略了。

其他时候,所有内容都被擦除并且不会再次绘制,除非我删除小部件并再次添加它。

我想了解为什么会出现这种问题。

小部件通过以下方式启动:

@Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
        Log.d(TAG_PROCESS, " onUpdate ");

        Intent intent = new Intent(context, UpdateService.class);
        intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); // embed extras so they don't get ignored
        intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);

        context.startService(intent);

    }

我通过这些方法更新 IntentService 中的小部件:

/** Updates all widgets with the given remoteViews instructions */
    protected static void updateAllWidgets(Context context, RemoteViews remoteView){
        ComponentName thisWidget = new ComponentName(context, WidgetActivity.class);
        AppWidgetManager manager = AppWidgetManager.getInstance(context);
        manager.updateAppWidget(thisWidget, remoteView);
    }

    /** Update a given widget (id) with the given remoteViews instructions */
    protected static void updateWidget(Context context, RemoteViews remoteView, int widgetId){
        AppWidgetManager manager = AppWidgetManager.getInstance(context);
        manager.updateAppWidget(widgetId, remoteView);
    }

好吧,看来上下文不是问题。

我使用了服务上下文。

问题是因为使用 manager.updateAppWidget(thisWidget, remoteView);有时会重新绘制所有小部件,因为正如文档所说,它指定了整个小部件描述。

解决方案是使用部分更新,因为我的应用程序小部件只对某些显示的视图管理多个部分更新:

/** Updates all widgets with the given remoteViews instructions */
    protected static void updateAllWidgets(Context context, RemoteViews remoteView){    
        ComponentName thisWidget = new ComponentName(context, WidgetActivity.class);
        AppWidgetManager manager = AppWidgetManager.getInstance(context);
        int[] allWidgetIds = manager.getAppWidgetIds(thisWidget);
        manager.partiallyUpdateAppWidget(allWidgetIds, remoteView);
    }

    /** Update a given widget (id) with the given remoteViews instructions */
    protected static void updateWidget(Context context, RemoteViews remoteView, int widgetId){
        AppWidgetManager manager = AppWidgetManager.getInstance(context);
        manager.partiallyUpdateAppWidget(widgetId, remoteView);
    }