在onCreate
函数中,您应该调用
/**
* In onCreate() we have to ensure that if the user presses BACK or cancelled the activity,
* then we should not add app widget.
*/
setResult(RESULT_CANCELED);
以确保如果您关闭配置活动,小部件不会添加到主页。以下代码显示了如何配置小部件。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* In onCreate() we have to ensure that if the user presses BACK or cancelled the activity,
* then we should not add app widget.
*/
setResult(RESULT_CANCELED);
setContentView(R.layout.activity_widget_settings);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null){
appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}
if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID){
finish();
return;
}
appWidgetManager = AppWidgetManager.getInstance(this);
views = new RemoteViews(this.getPackageName(), R.layout.my_app_widget);
}
配置后,不要忘记调用:
Intent widgetIntent = new Intent();
widgetIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
setResult(RESULT_OK,widgetIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);