gpt4 book ai didi

安卓小工具 : Not able to retain old values

转载 作者:太空狗 更新时间:2023-10-29 13:34:33 24 4
gpt4 key购买 nike

我会让它变得简单。我有我的小部件代码。我的小部件布局包含一个线性布局,其中有一个按钮。在我的小部件代码中,我用其中的一些值初始化了一个字符串列表。当我单击小部件中的按钮时,我必须用更多值更新我的列表。

所以,这是我的代码,

List<String> myList = null;
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
myList = new List<String>();
myList.add("1");
myList.add("2");
...
Intent intent = new Intent(context, getClass());
intent.setAction("CALL_UPDATE");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.button, pendingIntent);
....
}

@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("CALL_UPDATE")) {
Toast.makeText(context, "Intent received"+myList , 2000).show();
}
}

当按钮被点击时,广播被 onReceive() 正确接收。问题是,在 onReceive() 上,我看到我的列表为 null 而不是其中的某些值,因为之前添加了一些字符串对象。

有人能帮忙吗?

谢谢!拉胡尔。

最佳答案

文档说:

This has important repercussions to what you can do in an onReceive(Context, Intent) implementation: anything that requires asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation, but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous operation completes.

In particular, you may not show a dialog or bind to a service from within a BroadcastReceiver. For the former, you should instead use the NotificationManager API. For the latter, you can use Context.startService() to send a command to the service.

并且:

onReceive() is normally called within the main thread of its process, so you should never perform long-running operations in it (there is a timeout of 10 seconds that the system allows before considering the receiver to be blocked and a candidate to be killed). You cannot launch a popup dialog in your implementation of onReceive().

编辑:
AppWidgetProvider 是一个 BroadcastReceiver 并且它的实例(以及它的字段)将在它的生命周期后被删除。当您在 HomeScreen 中创建一个新的 widget 实例时,onUpdate AppWidgetProvider 的 onReceive 调用和此 AppWidgetProvider 实例的列表不为空。但是在调用 onReceive 之后(例如 10 秒)此实例将删除。当您单击按钮时,将创建 AppWidgetProvider 的第二个实例并且它是列表为空。
您可以保存类的列表 public static field 并在需要时检索它。

关于安卓小工具 : Not able to retain old values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12020859/

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