Android solves the problem of massive image downloads: Soft references must be understood as 4 points,

Source: Internet
Author: User

Android solves the problem of massive image downloads: Soft references must be understood as 4 points,

1. Strong, soft, weak, and virtual references of Objects
In order to control the lifecycle of objects more flexibly, you need to know the level 4 of object reference, from high to low: strong reference, soft reference, weak reference, and virtual reference.

Note: There are four differences:

(1) StrongReference)

Strong references are the most common references. If an object has a strong reference, the garbage collector will never recycle it. When the memory space is insufficient, the Java Virtual Machine would rather throw an OutOfMemoryError to terminate the program abnormally, and does not recycle strongly referenced objects at will to solve the problem of insufficient memory.

(2) SoftReference)

If an object only has soft references, the memory space is sufficient and the garbage collector will not recycle it. If the memory space is insufficient, the memory of these objects will be recycled. The object can be used by programs as long as the garbage collector does not recycle it. Soft references can be used to implement memory-sensitive high-speed cache (as shown in the following example ). Soft references can be used together with a ReferenceQueue. If the referenced objects are recycled by the garbage collector, the Java virtual machine adds this soft reference to the reference queue associated with it.

(3) WeakReference)

The difference between weak references and soft references is that only objects with weak references have a shorter life cycle. When the Garbage Collector thread scans the memory area under its jurisdiction, its memory will be recycled no matter whether the current memory space is sufficient or not. However, since the garbage collector is a thread with a low priority, it may not soon find objects with weak references. Weak references can be used together with a ReferenceQueue, the Java virtual machine adds this weak reference to the reference queue associated with it.

(4) PhantomReference)

As the name implies, "virtual references" are just the same as virtual ones, which are different from other types of references. Virtual references do not determine the object lifecycle. If an object only holds a virtual reference, it is the same as no reference and may be recycled by the garbage collector at any time. Virtual references are used to track the activity of objects recycled by the garbage collector. A difference between virtual and soft references and weak references is that virtual references must be used together with the reference Queue (ReferenceQueue. When the garbage collector is preparing to recycle an object, if it finds that it has a virtual reference, it will add this virtual reference to the reference queue associated with it before it recycles the object's memory.

ReferenceQueue queue = new ReferenceQueue ();
PhantomReference pr = new PhantomReference (object, queue );

The program can determine whether the referenced object has been added to the reference queue to check whether the referenced object is to be recycled. If the program finds that a virtual reference has been added to the reference queue, it can take necessary action before the memory of the referenced object is recycled.

2. Working Principle and function of soft reference
If an object only has soft references, the memory space is sufficient and the garbage collector will not recycle it. If the memory space is insufficient, the memory of these objects will be recycled. The object can be used by programs as long as the garbage collector does not recycle it.
Soft references can be used together with a ReferenceQueue. If soft references are recycled by the garbage collector, the Java virtual machine adds this soft reference to the reference queue associated with it.

3. Solutions for massive image download and memory management in android
Ideas:

(1) download images based on the path, save the images in imageCache (HashTable), and download the images to the local device;

(2) If the application memory is insufficient (SoftReference softReference decides not to use oom) When you download more than 200th images, the android virtual machine starts garbage collection. At this time, when an image is obtained, the image obtained by SoftReference softReference is null. If the image is null, you need to find the downloaded Image Based on the image id and path, and load the image directly, if you haven't downloaded it locally, you can download it directly from the network;

Can refer to: http://www.2cto.com/kf/201207/139035.html will be the image loading process encapsulated into a download device, focus on processing image download and cache problems; here is the use of a single thread download, you can use multithreading download speed faster;

The Code is as follows:

Public Drawable loadDrawable (final String imageUrl, final ImageCallBack imageCallback ){
If (imageCache. containsKey (imageUrl )){
SoftReference <Drawable> softReference = imageCache. get (imageUrl );
Drawable drawable = softReference. get ();
If (drawable! = Null ){
Return drawable;
}
}
Final Handler handler = new Handler (){
@ Override
Public void handleMessage (Message message ){
ImageCallback. imageLoaded (Drawable) message. obj, imageUrl );
}
};
New Thread (){
@ Override
Public void run (){
Drawable drawable = null;
Try {
Drawable = getDrawable (imageUrl );
ImageCache. put (imageUrl, new SoftReference <Drawable> (drawable ));
} Catch (Exception e ){
E. printStackTrace ();
}
Message message = handler. obtainMessage (0, drawable );
Handler. sendMessage (message );
}
}. Start ();
Return null;
}

Private Drawable getDrawable (String urlString) throws Exception {
If (! NetTools. isWifiConnected (context )){
GetImage = DataPreference. getIsAutoGetPicture (context );
} Else {
GetImage = true;
}
String fileName = urlString. substring (urlString. lastIndexOf ("/") + 1). trim ();
File cacheFile = null;
If (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {// sdcard mounted
CacheFile = new File (shopPicInSdcard + fileName );
If (getImage ){
If (! CacheFile. exists () & cacheFile. createNewFile () {// The cached file does not exist & the file is created and the cached image is downloaded to Sdcard.
InputStream inputStream = getInputStreamFromHttp (urlString );
WriteCacheFile2SDCard (cacheFile, readStream (inputStream ));
}
Return BitmapDrawable. createFromPath (shopPicInSdcard + fileName );
} Else {
Return null;
}

If (getImage ){
InputStream inputStream = getInputStreamFromHttp (urlString );
Return Drawable. createFromStream (inputStream, urlString );
} Else {
Return null;
}
}
}

4. android uses the image processing method in listview getView. It mainly optimizes the efficiency in listview.





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.