Android gets network pictures asynchronously and handles memory overflow problem Resolution _android

Source: Internet
Author: User
Test environment for adnroid more than 2.1.
1.androidmanifest.xml Permission Configuration
To add Internet access rights:
Copy Code code as follows:

<uses-permission android:name= "Android.permission.INTERNET"/>

2. Asynchronous Picture class Imagedownloadtask
Copy Code code 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;
/***
* Here to get the resolution size of the phone
* */
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 ();
}
}
/**
* Get online pictures via URL. such as: yun_qi_img/www.sexyxxx.com
* */
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 3 sentences are to handle the image overflow begin (If the overflow is not needed to deal with the opts.insamplesize=1 directly;)
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;
}
/**
* Data flow into btyle[] Array
* */
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 picture bitmap size exceeds VM budget (out of Memory 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 Call Code
Copy Code code as follows:

@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Imagedownloadtask imgtask =new imagedownloadtask ();
/** here is to get the resolution of the phone screen to handle the picture overflow problem. 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.execute ("Yun_qi_img/201201031116491.jpg", imageview_test);
}

4. Summary
Mainly through extends Asynctask<object, Object, bitmap> to achieve asynchronous.
Picture out of Memory memory overflow This operation, in practical applications should be considered calm extraction. It's easy to put in here for convenience. Overflow processing is actually to obtain the device resolution to compress the picture.

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.