Android widget update called twice after device boot

好久不见. 提交于 2019-12-10 11:02:58

问题


After device reboot I receive first APPWIDGET_ENABLED and then twice APPWIDGET_UPDATE. I spent quite some hours googling this without result. Is anybody experiencing the same? Have you found a way to avoid calling the update twice?

Here's some code:

    <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");
    }
}

回答1:


Have you found a way to avoid calling the update twice?

You have no control over how many times you are updated. That is up to the home screen and the app widget framework.




回答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
            }
        }
    }

}


来源:https://stackoverflow.com/questions/13363840/android-widget-update-called-twice-after-device-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!