Android asynchronously acquires and processes network images, leading to memory overflow. Solution

Source: Internet
Author: User

The test environment is Adnroid 2.1 or above.
1. AndroidManifest. xml permission Configuration:
Add Internet Access Permissions: Copy codeThe Code is as follows: <uses-permission android: name = "android. permission. INTERNET"/>

2. asynchronous image class ImageDownloadTask Copy codeThe Code is as follows: import java. io. ByteArrayOutputStream;
Import java. io. IOException;
Import java. io. InputStream;
Import java.net. MalformedURLException;
Import java.net. URL;
Import android. graphics. Bitmap;
Import android. graphics. BitmapFactory;
Import android. OS. AsyncTask;
Import android. widget. ImageView;
Public class ImageDownloadTask extends AsyncTask <Object, Object, Bitmap> {
Private ImageView imageView = null;
/***
* The Resolution of the mobile phone is obtained here.
**/
Public void setDisplayWidth (int width ){
_ Displaywidth = width;
}
Public int getDisplayWidth (){
Return _ displaywidth;
}
Public void setDisplayHeight (int height ){
_ Displayheight = height;
}
Public int getDisplayHeight (){
Return _ displayheight;
}
Public int getDisplayPixels (){
Return _ displaypixels;
}
Private int _ displaywidth = 480;
Private int _ displayheight = 800;
Private int _ displaypixels = _ displaywidth * _ displayheight;
@ Override
Protected Bitmap doInBackground (Object... params ){
// TODO Auto-generated method stub
Bitmap bmp = null;
ImageView = (ImageView) params [1];
Try {
String url = (String) params [0];
Bmp = getBitmap (url, _ displaypixels, true );
} Catch (Exception e ){
Return null;
}
Return bmp;
}
Protected void onPostExecute (Bitmap result ){
If (imageView! = Null & result! = Null ){
ImageView. setImageBitmap (result );
If (null! = Result & result. isRecycled () = false)
System. gc ();
}
}
/**
* Obtain the network segment through URL. Such as: http://www.xxxxxx.com/xx.jpg
**/
Public Bitmap getBitmap (String url, int displaypixels, Boolean isBig) throws MalformedURLException, IOException {
Bitmap bmp = null;
BitmapFactory. Options opts = new BitmapFactory. Options ();
InputStream stream = new URL (url). openStream ();
Byte [] bytes = getBytes (stream );
// These three statements are the begin for processing image overflow (if you do not need to handle overflow, directly opts. inSampleSize = 1 ;)
Opts. inJustDecodeBounds = true;
BitmapFactory. decodeByteArray (bytes, 0, bytes. length, opts );
Opts. inSampleSize = computeSampleSize (opts,-1, displaypixels );
// End
Opts. inJustDecodeBounds = false;
Bmp = BitmapFactory. decodeByteArray (bytes, 0, bytes. length, opts );
Return bmp;
}
/**
* Convert data streams to btyle [] Arrays
**/
Private byte [] getBytes (InputStream is ){
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
Byte [] B = new byte [2048];
Int len = 0;
Try {
While (len = is. read (B, 0, 2048 ))! =-1 ){
Baos. write (B, 0, len );
Baos. flush ();
}
} Catch (IOException e ){
E. printStackTrace ();
}
Byte [] bytes = baos. toByteArray ();
Return bytes;
}
/****
* Processing image bitmap size exceeds VM budget (Out Of Memory overflow)
*/
Private int computeSampleSize (BitmapFactory. Options options,
Int minSideLength, int maxNumOfPixels ){
Int initialSize = computeInitialSampleSize (options, minSideLength,
MaxNumOfPixels );
Int roundedSize;
If (initialSize <= 8 ){
RoundedSize = 1;
While (roundedSize <initialSize ){
RoundedSize <= 1;
}
} Else {
RoundedSize = (initialSize + 7)/8*8;
}
Return roundedSize;
}
Private int computeInitialSampleSize (BitmapFactory. Options options,
Int minSideLength, int maxNumOfPixels ){
Double w = options. outWidth;
Double h = options. outHeight;
Int lowerBound = (maxNumOfPixels =-1 )? 1: (int) Math. ceil (Math
. Sqrt (w * h/maxNumOfPixels ));
Int upperBound = (minSideLength =-1 )? 128: (int) Math. min (
Math. floor (w/minSideLength), Math. floor (h/minSideLength ));
If (upperBound <lowerBound ){
Return lowerBound;
}
If (maxNumOfPixels =-1) & (minSideLength =-1 )){
Return 1;
} Else if (minSideLength =-1 ){
Return lowerBound;
} Else {
Return upperBound;
}
}
}

3. Test the call code:Copy codeThe Code is as follows: @ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
ImageDownloadTask imgtask = new ImageDownloadTask ();
/** The resolution of the cell phone screen is used to handle image overflow. Begin */
DisplayMetrics dm = new DisplayMetrics ();
GetWindowManager (). getDefaultDisplay (). getMetrics (dm );
Imgtask. setDisplayWidth (dm. widthPixels );
Imgtask. setDisplayHeight (dm. heightPixels );
// End
ImageView imageView_test = (ImageView) findViewById (R. id. imageView_test );
Imgtask.exe cute ("http://pic.qukantu.com/big/7515/201201031116491.jpg", imageView_test );
}

4. Summary:
Extends AsyncTask <Object, Object, Bitmap> is used to implement Asynchronization.
The image Out Of Memory overflow operation should be extracted in a light manner in actual applications. This is for convenience. Overflow processing is actually to obtain the device resolution to compress the image.

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.