简体   繁体   中英

How to get appWidgetId in AppWidgetProvider?

I need to get the specific appWidgetId in AppWidgetProvider, not a bundle of appWidgetIds[] but the specific id which user clicked.

I could get it in its configure activity, using the "intent.getExtra().getInt(AppWidgetManager.APP_WIDGET_ID)" says like 504.

But it is so different in AppWidgetProvider, I will be appreciate it if anyone give me a hand.thanks in advance.

public class WidgetBox extends AppWidgetProvider implements Widget {

private int _widgetId = ?; // not appWidgetIds[]

}

You will get an array of Ids when the widget life cycle methods are called. You can simply iterate through the provided Ids like this:

@Override
public void onUpdate(final Context context, final AppWidgetManager appWidgetManager, final int[] appWidgetIds) {
    final int n = appWidgetIds.length;
    for( int i = 0; i < n; i++ ) {
        final int appWidgetId = appWidgetIds[i];
        // some logic here
    }
}

if you need to invoke some action, this is done using a pending intent during configuration (or a later update):

final RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
final Intent defineIntent = new Intent(context, YourTargetActivity.class);
defineIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 /* no request code */, defineIntent, 0);
views.setOnClickPendingIntent(R.id.view_id, pendingIntent);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM