With the below code, we get the list of all android widgets we have.
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
ComponentName thisAppWidget = new ComponentName(context, WidgetProvider.class);
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget);
But how i can get the id of the widget i just clicked? That means i have 3 or 4 widgets and when i click on one of them, i need to get id of the widget on which i clicked.
How to get it? I tried below function
public static int getWidgetId(Intent intent) {
Bundle extras = intent.getExtras();
int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
if (extras != null) {
appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
return appWidgetId;
}
But that's not working for me.
I assume you're setting a setOnClickPendingIntent()
to one of the layout elements in your Widget. Just set the appWidgetId
as an extra to your Intent
.
Following the basic idea:
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
int appWidgetId;
// Create an Intent for every Widget by iterating over the appWidgetIds array
// appWidgetIds array contains all Widgets
for (int i = 0; i < N; ++i) {
appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, MyClass.class);
// Add the appWidgetId to the Intent
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
// TODO init RemoteViews
remoteViews.setOnClickPendingIntent(R.id.myView, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
By doing this you can call your function getWidgetId in your Activity and should get the corresponding appWidgetId.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.