I am having trouble when I add a one or more instances of my widget to the home screen, remove them all, then add another.
Here is the code I use to set the "onClick" intent for each button (but开发者_运维百科ton is a resource)
protected void matchButtonToAction(Context context, RemoteViews views, String action, int button) {
Intent intent = new Intent(context, MightyToggleWidget.class);
intent.setAction(action);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
views.setOnClickPendingIntent(button, pendingIntent);
}
This only happens when I remove ALL instances and add one. If I add 2, remove 1 and add 1 it still works.
It is still receiving and reacting to battery events, but not other events (such as wifi state change events)
Any ideas what could be causing this? Thanks!
I have found the problem. The onEnabled event gets triggered at the start when the first widget is added. The onDisabled event gets triggered when the last widget is removed, but the onEnabled event does not get triggered when you try to add another "first" widget.
I had code that was similar to the examples in those events. This resulted in the packagemanager unregistering my AppWidgetProvider from receiving these events
@Override
public void onEnabled(Context context) {
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(new ComponentName(context.getPackageName(), getClass().getName()), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
}
@Override
public void onDisabled(Context context) {
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(new ComponentName(context.getPackageName(), getClass().getName()), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
}
I have added a static method that is called when the Configuration Activity adds a new instance that calls the PackageManager. Here is the code if anyone finds it useful
public static void newInstanceAdded(Context context, AppWidgetManager appWidgetManager, RemoteViews views, SharedPreferences prefs, int id){
ComponentName thisAppWidget = new ComponentName(context, MightyToggleWidget.class);
int ids[] = appWidgetManager.getAppWidgetIds(thisAppWidget);
if (ids.length == 1){
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(new ComponentName(context.getPackageName(), MightyToggleWidget.class.getName()), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
}
updateWidgetInstance(context, appWidgetManager, views, prefs, id);
}
Hope this helps!
精彩评论