Android multi-thread image download

Source: Internet
Author: User

Many times we need to download images from the remote server on the Android device for display. Today, android123 provides two better methods to download images remotely.
Method 1: access the remote server directly through the HTTP class provided by Android. Here, androidhttpclient is a new method in SDK 2.2, and the API level is 8. Note that static access can be called directly, if the SDK version is earlier, you can consider the Apache HTTP library. Of course, httpurlconnection or urlconnection can also be used.

Static bitmap downloadbitmapbycwj (string URL ){
Final androidhttpclient client = androidhttpclient. newinstance ("android123 ");
Final httpget getrequest = new httpget (URL );

Try {
Httpresponse response = client.exe cute (getrequest );
Final int statuscode = response. getstatusline (). getstatuscode ();
If (statuscode! = Httpstatus. SC _ OK ){
Log. E ("cwjdebug", "error" + statuscode + "while retrieving bitmap from" + URL );
Return NULL;
}

Final httpentity entity = response. getentity ();
If (entity! = NULL ){
Inputstream = NULL;
Try {
Inputstream = entity. getcontent ();
Final Bitmap bitmap = bitmapfactory. decodestream (inputstream );
Return bitmap;
} Finally {
If (inputstream! = NULL ){
Inputstream. Close ();
}
Entity. consumecontent ();
}
}
} Catch (exception e ){
Getrequest. Abort ();
Log. E ("android123debug", "error while retrieving bitmap from" + URL, E. tostring ());
} Finally {
If (client! = NULL ){
Client. Close ();
}
}
Return NULL;
}

Here, the android Development Network reminds everyone that the decodestream method of the bitmapfactory class cannot obtain complete data when the network times out or is slow, here, we use the Skip method inherited from the filterinputstream class to forcibly implement the data in the flush stream. The main principle is to check whether the data ends at the end of the file and tell the HTTP class whether to continue.

Static class flushedinputstream extends filterinputstream {
Public flushedinputstream (inputstream ){
Super (inputstream );
}

@ Override
Public long SKIP (long n) throws ioexception {
Long totalbytesskipped = 0l;
While (totalbytesskipped <n ){
Long bytesskipped = in. Skip (n-totalbytesskipped );
If (bytesskipped = 0l ){
Int byte = read ();
If (byte <0 ){
Break; // we reached EOF
} Else {
Bytesskipped = 1; // we read one byte
}
}
Totalbytesskipped + = bytesskipped;
}
Return totalbytesskipped;
}
}

Method 2: asynctask asynchronous task

Google provided an asynctask class from Android 1.5 to help developers process asynchronous download implementation. Compared with thread, it can run in the UI thread, its internal implementation is derived from concurrent in Java 5, and the overall implementation is relatively reliable, that is, the resource usage is slightly larger. However, it is easier to use. Here, the download method of the image-like imagedownloader class can be used to perform operations such as UI display. Parameter 1 URL is the URL of the file on the remote server, and the second parameter is the imageview object, you can directly display the downloaded Remote Image in the imageview.

Public class imagedownloader {

Public void download (string URL, imageview ){
Bitmapdownloadertask task = new bitmapdownloadertask (imageview );
Task.exe cute (URL );
}
}

}

For the specific implementation of the asynctask class, we recommend that you use weak references to save the imageview object in order to provide sufficient space storage for the JVM.

Class bitmapdownloadertask extends asynctask <string, void, bitmap> {
Private string URL;
Private Final weakreference <imageview> imageviewreference; // use weakreference to solve memory problems

Public bitmapdownloadertask (imageview ){
Imageviewreference = new weakreference <imageview> (imageview );
}

@ Override
Protected bitmap doinbackground (string... Params) {// The actual download thread is actually a concurrent thread internally, so it will not be blocked

Return downloadbitmap (Params [0]);

}

@ Override
Protected void onpostexecute (Bitmap bitmap) {//
If (iscancelled ()){
Bitmap = NULL;
}

If (imageviewreference! = NULL ){
Imageview = imageviewreference. Get ();
If (imageview! = NULL ){
Imageview. setimagebitmap (Bitmap); // After downloading, set imageview to the bitmap object you just downloaded.
}
}
}
}

Reference: http://androidssh.iteye.com/blog/731356

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.