我无法在 onReceive() 中获取单击的小部件的 ID。始终返回 0。这是我的代码:
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(WIDGET_BUTTON)) {
int widgetId = intent.getIntExtra( AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
log("WID ID" + widgetId);
我从 Android Developers Docs 获取代码,我不知道为什么它不起作用..
答案:
我想:
AppWidgetManager mgr = AppWidgetManager.getInstance(context);
所以我的代码是这样的:
@Override
public void onReceive(Context context, Intent intent) {
AppWidgetManager mgr = AppWidgetManager.getInstance(context);
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_main);
if (intent.getAction().equals(WIDGET_BUTTON)) {
Bundle extras = intent.getExtras();
int widgetId = 0;
if (extras != null && extras.containsKey(AppWidgetManager.EXTRA_APPWIDGET_ID))
widgetId = intent.getIntExtra(mgr.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
log("1 - WID ID" + widgetId);