This article is your own study notes, welcome reprint, but please specify the source:http://blog.csdn.net/jesson20121020
After android4.0, the network request operation is not allowed in the main thread, otherwise a networkonmainthreadexception exception will occur. And in order to solve the android4.0 can make network requests, there are two ways to solve, in order to read the image of the network as an example, first look:
When the button is clicked, the network picture of the specified address is loaded in the ImageView to be displayed.
To read a network image:1. Obtain the network picture data of the specified address
There are two ways to read the network of the specified address into bitmap and then load the display through ImageView.
1). Decode 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 Au To-generated catch Blocke.printstacktrace ();} return bitmap;}
2). Writes the input stream to the input stream via byte data and converts it to bitmap via the Bitmapfactory.decodebytearray () method
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. The resulting bitmap load is displayed in the ImageView.
At the beginning, it is mentioned that the android4.0 can not be directly in the main thread of the network request and so on, so in order to load the network picture into the ImageView, there are two ways, as follows:
Method 1: Do not create a new thread;
Directly in the OnCreate () method, add the following two lines of code, and then directly in the main thread to read the operation of the network picture.
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 only apply to android4.0, if you targetsdk under 4.0, you can not add these two lines of code, directly in the main thread to read the network picture operation, but this method is not recommended.
The next step is to get bitmap loaded into ImageView with the first two methods, the main code is as follows:
<span style= "White-space:pre" ></span>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 also does not allow UI to be updated in non-UI threads, it is not possible to write Imageview.setimagebitmap () directly in the thread, which is due to handler, because handler is running in the main thread, Therefore, the Read network data is used to notify handler by using a message to notify the update UI. The main code is as follows:
<span style= "White-space:pre" ></span>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 Messag E (); msg.what = 1;//mbitmap = GetData (); mbitmap = GetData1 (); Handler.sendmessage (msg);}};
Next, you create a new thread in the button's click event and start.
<span style= "White-space:pre" ></span>button = (Button) Findviewbyid (R.id.button); Button.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubnew Thread (runnable). Start ();}});
Finally, give the layout file 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/activity_ Horizontal_margin " android:paddingright=" @dimen/activity_horizontal_margin " android:paddingtop=" @dimen /activity_vertical_margin " tools:context=". Mainactivity "><button android:id=" @+id/button " android:layout_width=" Wrap_content " android: layout_height= "Wrap_content" android:text= "read network picture" /> <imageview android:id= "@+id/ ImageView " android:layout_width=" match_parent " android:layout_height=" wrap_content " /></ Relativelayout>
Android Read Network pictures