gpt4 book ai didi

android - 对象的 'strong' 引用是什么意思,为什么我们应该将对 OnSharedPreferenceChangeListener 的引用存储在对象的数据中?

转载 作者:搜寻专家 更新时间:2023-11-01 07:50:06 25 4
gpt4 key购买 nike

来自 this guide在首选项上,

Caution: When you call registerOnSharedPreferenceChangeListener(), the preference manager does not currently store a strong reference to the listener. You must store a strong reference to the listener, or it will be susceptible to garbage collection.

We recommend you keep a reference to the listener in the instance data of an object that will exist as long as you need the listener.

  1. 此处的strong引用与(仅)引用相对是什么意思?
  2. 他们建议将引用保留在实例中一个对象的数据。这意味着还有其他方法可以保持引用(在 static 变量中?)。所以问题是为什么他们建议在对象的实例数据中保留引用?

最佳答案

简单地说—— WeakReference是一个java概念/类。仅使用弱引用引用的对象在 GC 传递中被垃圾收集。

另一方面,强引用/您一直使用的引用(例如 Integer a = 20;)不会让 GC 收集/释放对象。

所以在你的情况下,假设您向首选项管理器注册了一个 OnSharedPreferenceChangeListener,首选项管理器会将其存储为非强引用(可能是弱引用)。

prefs.registerOnSharedPreferenceChangeListener(
//anonymous object, you don't hold the reference to the listener you create - this is susceptible to get garbage collected
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// listener implementation
}
});

这意味着每当 GC 发生时,监听器对象将被收集,因为在任何地方都没有对监听器对象的强引用。因此,偏好管理器将失去对它的引用保留您注册的监听器,此后您将不会收到任何偏好更改回调。

但是 - 如果您自己在代码中的某处存储对监听器的强引用,它将使 GC 跳过对监听器对象的收集/释放,因为至少有一个对该对象的强引用。这将使您可以继续接收来自首选项管理器的那些回调。

public class ABC extends Activity{
SharedPreferences.OnSharedPreferenceChangeListener listener; // this object will last until the enclosing activity is destroyed.

...onCreate(Bundle b){
prefs.registerOnSharedPreferenceChangeListener(
// Create a **strong** reference to the listener
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// listener implementation
}
});
}

关于android - 对象的 'strong' 引用是什么意思,为什么我们应该将对 OnSharedPreferenceChangeListener 的引用存储在对象的数据中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35935936/

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