【问题标题】:Android App Widget - which context to useAndroid App Widget - 使用哪个上下文
【发布时间】:2015-09-11 20:15:22
【问题描述】:

我有一个应用小部件,它在接收更新时启动一个 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);
    }

【问题讨论】:

  • 也许显示一些代码?
  • @ci_ 我添加了一些代码

标签: android android-context android-appwidget intentservice appwidgetprovider


【解决方案1】:

嗯,上下文似乎不是问题。

我使用了服务上下文。

问题是因为使用 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);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多