Weak references (WeakReference)
- Used for non-required objects. Objects that are associated with a weak reference can only survive until the next garbage collection occurs. When the garbage collector is working, the objects associated with a weak reference are reclaimed regardless of whether the current memory is sufficient.
1. Non-UI threading bitmap (can be replaced with other objects)
The following is from the official website
class bitmapworkertask extends asynctask { Private FinalWeakReference imageviewreference;//Pay attention to the final Private intdata =0; PublicBitmapworkertask (ImageView ImageView) {//Use WeakReference to ensure ImageView can be recycledImageviewreference =NewWeakReference (ImageView); }//Decode image in background.@OverrideprotectedBitmap doinbackground (Integer ... params) {data = params[0];returnDecodesampledbitmapfromresource (Getresources (), data, -, -)); }//When finished, see if ImageView is still in, updated in the UI.@Overrideprotected voidOnPostExecute (Bitmap Bitmap) {if(Imageviewreference! =NULL&& Bitmap! =NULL) {FinalImageView ImageView = Imageviewreference.get ();if(ImageView! =NULL) {Imageview.setimagebitmap (bitmap); } } }}
2. Managing activity and Handler Communications
The following is the code snippet in my project, complete code
//Use static inner classes to prevent implicit references to external classes Static class weakreferencehander extends Handler { //The acitivity is managed with WeakReference. Private FinalWeakreference<shareuploadactivity> mactivity; PublicWeakreferencehander (shareuploadactivity activity) {mactivity =NewWeakreference<shareuploadactivity> (activity); } @Override Public voidHandlemessage (Message msg) {if(Mactivity.get ()! =NULL) {Mactivity.get (). Handlereceivemessage (msg); } } }
If this is not the case, consider that if a child thread performs a more time-consuming operation (which is not finished), the UI thread finishes (), but the GC cannot recycle it because there is a handler reference.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
WeakReference use in Android