2

设备重新启动后,我收到第一个 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");
    }
}
4

2 回答 2

2

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

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

于 2012-11-13T17:18:30.360 回答
-1
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
            }
        }
    }

}
于 2013-05-25T12:43:45.460 回答