Android-Network Communication (example of reading network images)
The. xml Code is as follows:
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 to use this. img = (ImageView) super. findViewById (R. id. myimg); 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 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:
Run