如果您正在从Provider类进行更新,则可以从onUpdate()方法中获取小部件ID,如下所示:
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
}
如果你要从 ConfigurationActivity 更新小部件,可以在 onCreate 方法中获取小部件的 id,方法如下:
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
让您的小部件从小部件布局中的按钮/图像视图启动ConfigurationActivity
Intent configurationIntent = new Intent(WidgetBarConfiguration.this, WidgetBarConfiguration.class);
configurationIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
PendingIntent configurationPendingIntent = PendingIntent.getActivity(WidgetBarConfiguration.this, 0, configurationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews views = new RemoteViews(WidgetBarConfiguration.this.getPackageName(), R.layout.widget_bar_layout);
views.setOnClickPendingIntent(R.id.imageViewSettings, configurationPendingIntent);
mWidgetManager.updateAppWidget(mAppWidgetId, views);
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();
AndroidManifest.xml
<activity
android:name=".WidgetBarConfiguration"
android:label="@string/title_activity_widget_configuration"
android:launchMode="singleInstance"
android:theme="@style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
</intent-filter>
</activity>
看到
lauchMode = "singleInstance"
,可以确保只有ConfigurationActivity的布局在点击时出现,没有其他活动布局附加。