I know I am a bit late but things have changed and the code provided by Leonardo Garcia Fischer doesn't work anymore.
Here is the updated version:
final int appWidgetHostId = 23456;
final int REQUEST_BIND_APPWIDGET = 12345;
AppWidgetHost widgetHost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
widgetHost = new AppWidgetHost(getApplicationContext(), appWidgetHostId);
widgetHost.startListening();
}
@Override
protected void onDestroy() {
widgetHost.stopListening();
super.onDestroy();
}
void configureWidget(int appWidgetId) {
widgetHost.startAppWidgetConfigureActivityForResult(this, appWidgetId, 0, 0, null);
}
AppWidgetProviderInfo getWidgetProviderInfo(String packageName, int widgetPosition) {
AppWidgetManager manager = AppWidgetManager.getInstance(this);
List<AppWidgetProviderInfo> infos = manager.getInstalledProvidersForPackage(packageName, Process.myUserHandle());
return infos.get(widgetPosition);
}
AppWidgetHostView getWidgetHostView(AppWidgetProviderInfo info) {
int appWidgetId = widgetHost.allocateAppWidgetId();
AppWidgetManager manager = AppWidgetManager.getInstance(getApplicationContext());
boolean canBindWidgets = manager.bindAppWidgetIdIfAllowed(appWidgetId, info.provider);
if(!canBindWidgets) {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider);
startActivityForResult(intent, REQUEST_BIND_APPWIDGET);
}
AppWidgetHostView widgetHostView = widgetHost.createView(getApplicationContext(), appWidgetId, info);
if(info.configure != null) {
configureWidget(appWidgetId);
}
return widgetHostView;
}
Now, if you want to create an app widget, first you call getWidgetProviderInfo()
by specifying which package you want to get your app widgets from and which widget you want (because there may be more than one). Then, you pass the result to getWidgetHostView
which will create the widget and launch the configure activity if there is one. Then, you can use the AppWidgetHostView it returns and put it in a linear layout for example. Here is a more complete example:
void createMyWidget() {
String packageName = com.xxx.xxx;
AppWidgetProviderInfo widgetInfo = getWidgetProviderInfo(packageName, 0);
AppWidgetHostView widgetHostView = getWidgetHostView(widgetInfo);
//Add the widgetHostView to your container.
}
Finally, if you want to reconfigure your app widget, you can do so by calling configureWidget
and passing its app widget id as a parameter. It will relauch the configure activity (if there is one; that's why you should verify if it exists first by looking at the widget's provider info, just like in the getWidgetHostView
function).