我让用户通过打开窗口小部件意图从窗口小部件列表中选择窗口小部件
public void initAppWidget() {
try {
mAppWidgetManager = AppWidgetManager.getInstance(this);
mAppWidgetHost = new AppWidgetHost(this, Constants.APPWIDGET_HOST_ID);
} catch
(Exception e) {
e.printStackTrace();
}
}
public void selectWidget() {
int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
startActivityForResult(pickIntent, Constants.SELECT_APPWIDGET);
}
当用户从列表中选择窗口小部件时,将调用 onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case Constants.SELECT_APPWIDGET:
if (resultCode == RESULT_OK) {
configureWidget(data);
} else if (resultCode == RESULT_CANCELED && data != null) {
int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
if (appWidgetId != -1) {
mAppWidgetHost.deleteAppWidgetId(appWidgetId);
}
}
break;
case Constants.REQUEST_CREATE_APPWIDGET:
if (resultCode == RESULT_OK) {
createWidget(data);
} else if (resultCode == RESULT_CANCELED && data != null) {
int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
if (appWidgetId != -1) {
mAppWidgetHost.deleteAppWidgetId(appWidgetId);
}
}
break;
}
}
public void configureWidget(Intent data) {
Bundle extras = data.getExtras();
int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
if (appWidgetInfo.configure != null) {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
intent.setComponent(appWidgetInfo.configure);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
startActivityForResult(intent, Constants.REQUEST_CREATE_APPWIDGET);
} else {
createWidget(data);
}
}
最后,createWidget函数将小部件视图添加到线性布局
public void createWidget(Intent data) {
int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
AppWidgetHostView hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
hostView.setAppWidget(appWidgetId, appWidgetInfo);
hostView.setId(id);
ll_widgets_list.addView(hostView);
id++;
}
但有些小工具没有点击,例如模拟时钟。像谷歌驱动器这样的小部件包含其他视图,可以点击并且工作正常。每当用户通过它执行任何操作时,Widget都不会更新。
答案 0 :(得分:0)
mAppWidgetHost.startListening();
initAppWidget()函数中缺少此行,该函数侦听窗口小部件的更改。