Removing AppWidgets programmatically

2019-01-09 04:15发布

问题:

I'm having the hardest time figuring out how to remove home screen AppWidget's programmatically (i.e. without the user actually dragging one into the trash). As an example, consider an app that can have multiple accounts, with any number of widgets for each account - once an account is removed, widget should be deleted as well.

I've tried following an obscure example from http://www.netmite.com/android/mydroid/cupcake/frameworks/base/services/java/com/android/server/AppWidgetService.java, but that doesn't seem to even trigger OnDeleted, much less remove the AppWidget from the home screen.

Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_DELETED);
intent.setComponent(info.componentName); // references AppWidgetProvider's class
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
sendBroadcast(intent);

Does anyone have any advice on how this can be accomplished? An example would be the bee's knees. Thanks.

回答1:

You cannot add or remove app widgets from the home screen. Only the user can do that.

Any app widgets tied to a deleted account could show a different account, or adopt some "(account deleted)" look that would trigger the user to get rid of the app widget or reconfigure it.



回答2:

I'm pretty sure this should work:

int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName("com.example",
                        "com.example.Widget"));
AppWidgetHost host = new AppWidgetHost(ctx, 0);
host.deleteAppWidgetId(appWidgetIds[0]);