0
我讓用戶從窗口小部件列表中選擇部件工作由用戶添加小部件與點擊未打開的意圖的小部件Android應用
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就不會更新。