【问题标题】:Android widget update called twice after device boot设备启动后两次调用 Android 小部件更新
【发布时间】:2012-11-13 15:43:32
【问题描述】:

设备重新启动后,我收到第一个 APPWIDGET_ENABLED,然后 两次 APPWIDGET_UPDATE。 我花了很多时间在谷歌上搜索这个没有结果。 有没有人有同样的经历?您是否找到避免两次调用更新的方法?

这里有一些代码:

    <receiver android:name=".Widget" android:label="@string/app_name">
        <intent-filter>
             <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> 
        </intent-filter>
        <meta-data android:name="android.appwidget.provider" android:resource="@xml/button_widget_provider" />
    </receiver>



public void onReceive(final Context context, final Intent intent) {
    super.onReceive(context, intent);
    final String action = intent.getAction();

    if  (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action) ) {
        Log.i(TAG, "update");
    } else if (AppWidgetManager.ACTION_APPWIDGET_ENABLED.equals(action) ) {
        Log.i(TAG, "enabled");
    }
}

【问题讨论】:

    标签: android widget boot reboot


    【解决方案1】:

    您是否找到了避免两次调用更新的方法?

    您无法控制更新的次数。这取决于主屏幕和应用小部件框架。

    【讨论】:

    • 您的意思是即使我在桌面上只有 1 个小部件实例,我也可以更新 n 次(而不仅仅是 2 次)?
    • @sara:是的。无法保证主屏幕会请求更新多少次。
    • 很高兴听到我的小部件依赖于非确定性平台!有没有办法解决这个问题?
    • @sara:因为我不知道你的问题是什么,所以我无法回答这个问题。应用小部件不应该关心它们更新了多少次。
    • 我认为他们确实在乎,因为在每次更新期间,他们都会执行消耗时间和资源的任务。多次执行相同的任务简直是浪费。
    【解决方案2】:
    import java.util.ArrayList;
    
    import android.appwidget.AppWidgetManager;
    import android.appwidget.AppWidgetProvider;
    import android.content.Context;
    
    public class CopyOfWidgetProvider extends AppWidgetProvider {
    
        private static ArrayList<Integer> widgets = new ArrayList<Integer>();
    
        @Override
        public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] widgetIDs) {
            super.onUpdate(context, appWidgetManager, widgetIDs);
    
            for (int widgetID : widgetIDs) {
                if (!widgets.contains(widgetID)) {
                    widgets.add(widgetID);
                    // this code will run only ONCE after reboot
                    // loop is necessary in cases where there were more than one
                    // instances of widget before reboot
                }
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-27
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多