问题
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