The. XML code is as follows:
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:layout_width=" fill_parent " android:layout_height=" fill_parent " android:o rientation= "vertical" > <imageview android:id= "@+id/myimg" android:layout_width= "Wrap_content " android:layout_height=" wrap_content "/> </LinearLayout>
The. Java program is as follows:
Package Org.lxh.demo;import Java.io.bytearrayoutputstream;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.url;import Android.app.activity;import Android.app.AlertDialog;import Android.app.dialog;import Android.content.dialoginterface;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.view.onfocuschangelistener;import Android.widget.Button; Import Android.widget.edittext;import Android.widget.imageview;import Android.widget.textview;public class Hello Extends Activity {private static final String path= "http://img1.gtimg.com/11/1176/117678/11767886_1200x1000_0.jpg"; Private ImageView img=null;public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);// Life cycle Method Super.setcontentview (R.layout.main); Set the layout manager this.img= (ImageView) Super.findviewbyid (r.id.myimg) to be used; try{byte data[]=this.geturldata (); Bitmap Bm=bitmapFactory.decodebytearray (data, 0, data.length); This.img.setImageBitmap (BM);} catch (Exception e) {}}private byte[] Geturldata () throws Exception {Bytearrayoutputstream bos=null; URL url=new url (PATH); bos=new Bytearrayoutputstream (); byte[] Data=new byte[1024]; HttpURLConnection conn= (httpurlconnection) url.openconnection (); InputStream input=conn.getinputstream (); int len=0; while ((Len=input.read (data))!=-1) {bos.write (Data,0,len);} return Bos.tobytearray ();}}
You need to configure permissions:
<uses-permission android:name= "Android.permission.INTERNET"/>
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Org.lxh.demo "android:versioncode=" 1 "android:versionname=" 1.0 "><USES-SDK android: minsdkversion= "/><strong><span style=" color: #ff0000; " ><uses-permission android:name= "Android.permission.INTERNET"/></span></strong>< Application android:icon= "@drawable/icon" android:label= "@string/app_name" ><activity android:name= ". Hello "android:label=" @string/app_name "><intent-filter><action android:name=" Android.intent.action.MAIN "/><category android:name=" Android.intent.category.LAUNCHER "/></ Intent-filter></activity></application></manifest>
Run
android--network Communication (example of reading a network picture)