Android reads network images,

Source: Internet
Author: User

Android reads network images,

This article is my learning notes, welcome to reprint, but please note the Source: http://blog.csdn.net/jesson20121020

After android4.0, network request operations in the main thread are no longer allowed. Otherwise, a NetworkOnMainThreadException occurs. In order to solve the problem of network requests on Android, there are two ways to solve the problem. For example, to read images from the network, first look:


When you click the button, the network image of the specified address is loaded into the imageVIew for display.

Read network image: 1. Obtain network image data of the specified address

There are two ways to read the network of the specified address to Bitmap, and then load the display through imageView.

1). decodes the input stream into Bitmap

private static String path = "http://221.203.108.70:8080/jxzy/UploadFiles_4517/201005/2010052615165701.jpg";

public Bitmap getData(){Bitmap bitmap = null;try {URL url = new URL(path);URLConnection conn = url.openConnection();conn.connect();InputStream is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is);} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return bitmap;}
2). Write the input stream to the input stream using byte data, and convert it to Bitmap Using BitmapFactory. decodeByteArray ().

public Bitmap getData1(){Bitmap bitmap = null;ByteArrayOutputStream bos = null;try {URL url = new URL(path);URLConnection conn = url.openConnection();InputStream is = conn.getInputStream();bos = new ByteArrayOutputStream();byte[] data = new byte[1024];int len = 0;while((len = is.read(data))!= -1){bos.write(data, 0, len);}byte[] data1 = bos.toByteArray();bitmap = BitmapFactory.decodeByteArray(bos.toByteArray(), 0, data1.length);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return bitmap;}


2. Load the obtained Bitmap to the imageView.

As mentioned at the beginning, you cannot directly perform network requests and other operations in the main thread on top of android4.0. Therefore, there are two methods to load network images to ImageView, as shown below:

Method 1: No new thread is created;

Directly Add the following two lines of code to the onCreate () method, and then read the network image directly in the main thread.

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());   

With these two lines of code, of course, these are only applicable to android4.0. If the targetSDK is under 4.0, you can skip these two lines of code, read network images directly in the main thread, but this method is not recommended.

The next step is to load the Bitmap obtained by the first two methods into the imageView. The main code is as follows:

imageView = (ImageView)findViewById(R.id.imageView);button = (Button)findViewById(R.id.button);button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubimageView.setImageBitmap(getData());}});


Method 2: Use Thread + Handler

Because android does not allow updating the UI in a non-UI thread, you cannot directly update the imageView. setImageBitmap () is used to write the thread. Handler is running in the main thread. Therefore, when reading network data, the Message is used to notify Handler to notify the updated UI. The main code is as follows:

Handler handler = new Handler(){public void handleMessage(Message msg) {if(msg.what == 1){imageView.setImageBitmap(mBitmap);}};};Runnable runnable = new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubMessage msg = new Message();msg.what = 1;//mBitmap = getData();mBitmap = getData1();handler.sendMessage(msg);}};
Next, create a thread in the button click event and start it.
button = (Button)findViewById(R.id.button);button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubnew Thread(runnable).start();}});

Finally, the layout file is given as follows:

<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" android: paddingBottom = "@ dimen/activity_vertical_margin" android: paddingLeft = "@ dimen/plugin" android: paddingRight = "@ dimen/plugin" android: paddingTop = "@ dimen/plugin" tools: context = ". mainActivity "> <Button android: id =" @ + id/button "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: text = "read network image"/> <ImageView android: id = "@ + id/imageView" android: layout_width = "match_parent" android: layout_height = "wrap_content"/> </RelativeLayout>











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.