我正在开发一个启动器。它让用户从列表中添加小部件,效果很好。当用户在屏幕上添加一个小部件时,我将有关小部件的信息(PackageName、ClassName 和它在屏幕上的坐标)存储在我的数据库中。
当应用程序重新启动(或设备本身)时,我通过代码添加那些(用户选择的)小部件:
// APPWIDGET_HOST_ID is any number you like
appWidgetManager = AppWidgetManager.getInstance(this);
appWidgetHost = new AppWidgetHost(this, APPWIDGET_HOST_ID);
AppWidgetProviderInfo newAppWidgetProviderInfo = new AppWidgetProviderInfo();
// Get an id
int appWidgetId = appWidgetHost.allocateAppWidgetId();
// Get the list of installed widgets
List<AppWidgetProviderInfo> appWidgetInfos = new ArrayList<AppWidgetProviderInfo>();
appWidgetInfos = appWidgetManager.getInstalledProviders();
for(int j = 0; j < appWidgetInfos.size(); j++)
{
if (appWidgetInfos.get(j).provider.getPackageName().equals(PackageName) && appWidgetInfos.get(j).provider.getClassName().equals(ClassName))
{
// Get the full info of the required widget
newAppWidgetProviderInfo = appWidgetInfos.get(j);
break;
}
}
// Create Widget
AppWidgetHostView hostView = appWidgetHost.createView(this, appWidgetId, newAppWidgetProviderInfo);
hostView.setAppWidget(appWidgetId, newAppWidgetProviderInfo);
// Add it to your layout
RelativeLayout widgetLayout = (RelativeLayout) findViewById(R.id.widgetLayout);
widgetLayout.addView(hostView);
小部件已成功添加到布局中,但似乎未启用/更新。它不响应点击(例如,模拟时钟)并且不显示任何数据(例如,音乐播放器小部件),尽管我已经放了这个:
@Override
protected void onStart() {
super.onStart();
appWidgetHost.startListening();
}
@Override
protected void onStop() {
super.onStop();
appWidgetHost.stopListening();
}
我坚持了很长时间。搜索了很多,但似乎我是这个世界上唯一有这个问题的人。