gpt4 book ai didi

android - onReceive 将始终接收最后一个 appWidgetId,即使正在按下不同的实例 widget

转载 作者:行者123 更新时间:2023-11-29 15:18:36 25 4
gpt4 key购买 nike

我有以下代码。我试图在我的主屏幕中放置 2 个小部件实例。

这是在放置了 2 个小部件实例后正在打印的日志。

onUpdate START
onUpdate 170
onUpdate START
onUpdate 171

当我依次点击第一个小部件和第二个小部件时,我预计将分别打印 170 和 171。然而,这就是我得到的。

onReceive 171  <-- I'm expecting 170 to be printed.
onReceive 171

我的代码有什么问题吗?或者,我有错误的期望?

public class MyAppWidgetProvider extends AppWidgetProvider {    
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.i("CHEOK", "onUpdate START");

for (int appWidgetId : appWidgetIds) {
Log.i("CHEOK", "onUpdate " + appWidgetId);

RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout_inverse_holo_light);

// Register an onClickListener
Intent refreshIntent = new Intent(context, JStockAppWidgetProvider.class);
refreshIntent.setAction(REFRESH_ACTION);
refreshIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(context, 0, refreshIntent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.refresh_button, refreshPendingIntent);

appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
}

@Override
public void onReceive(Context context, Intent intent) {
AppWidgetManager mgr = AppWidgetManager.getInstance(context);
if (intent.getAction().equals(REFRESH_ACTION)) {
int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);

Log.i("CHEOK", "onReceive " + appWidgetId);

// How can I access my remoteView?
// During onUpdate, is saving all the remoteViews in local member
// Map<appWidgetId, remoteView> a good idea?
}
super.onReceive(context, intent);
}

private static final String REFRESH_ACTION = "org.yccheok.jstock.gui.widget.MyAppWidgetProvider.REFRESH_ACTION";
}

最佳答案

这是因为你的两个PendingIntent被同等对待,所以创建第二个会替换第一个,引用: http://developer.android.com/reference/android/content/Intent.html#filterEquals%28android.content.Intent%29

Determine if two intents are the same for the purposes of intent resolution (filtering). That is, if their action, data, type, class, and categories are the same. This does not compare any extra data included in the intents.

所以你的只是 Extra 的不同,这是行不通的。尝试使用 setData 进行设置。

refreshIntent.setData(Uri.parse(refreshIntent.toUri(Intent.URI_INTENT_SCHEME)));

关于android - onReceive 将始终接收最后一个 appWidgetId,即使正在按下不同的实例 widget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21311917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com