Android uses weak references (WeakReference) or soft references (SoftReference)

Here is sample code using weak and soft references:

1. Weak Reference (WeakReference) sample code:

import java.lang.ref.WeakReference;

public class MyActivity extends AppCompatActivity {
    
    
    private WeakReference<SomeObject> weakRef;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        // 创建弱引用对象
        SomeObject obj = new SomeObject();
        weakRef = new WeakReference<>(obj);
        // 使用弱引用对象进行操作
        SomeObject refObj = weakRef.get();
        if (refObj != null) {
    
    
            // 对 refObj 进行操作
        } else {
    
    
            // refObj 已经被回收
        }
    }

    @Override
    protected void onDestroy() {
    
    
        super.onDestroy();
        // 清除对弱引用对象的引用
        weakRef.clear();
    }
}

In the above code, we create an instance of SomeObject class and use WeakReference to hold a weak reference to this object. When you need to use the object, use the weakRef.get() method to obtain the reference of the weak reference object. If the object has not been recycled, you can perform corresponding operations. In the onDestroy() method, use the clear() method to clear the reference to the weakly referenced object.

2. SoftReference sample code:

import java.lang.ref.SoftReference;

public class MyActivity extends AppCompatActivity {
    
    
    private SoftReference<SomeObject> softRef;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        // 创建软引用对象
        SomeObject obj = new SomeObject();
        softRef = new SoftReference<>(obj);
        // 使用软引用对象进行操作
        SomeObject refObj = softRef.get();
        if (refObj != null) {
    
    
            // 对 refObj 进行操作
        } else {
    
    
            // refObj 已经被回收
        }
    }

    @Override
    protected void onDestroy() {
    
    
        super.onDestroy();
        // 清除对软引用对象的引用
        softRef.clear();
    }
}

In the above code, we also create an instance of SomeObject class and use SoftReference to hold the object's soft reference. The usage is similar to that of weak references. When an object needs to be used, the softRef.get() method is used to obtain the reference of the soft reference object and perform corresponding operations. In the onDestroy() method, use the clear() method to clear the reference to the soft reference object.

It is worth noting that since soft references are automatically reclaimed when memory is insufficient, it is necessary to carefully judge whether the soft reference object is null in actual use to avoid null pointer exceptions.

Supongo que te gusta

Origin blog.csdn.net/ZQ200720/article/details/132333220
Recomendado
Clasificación