Android Network image viewing example
1. layout File
2. Implementation in the main program
Package com. wzw. netphoto; import java. io. inputStream; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL; import android. OS. bundle; import android. app. activity; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. view. menu; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. editText; import android. widget. imageView; import android. widget. toast; public class MainActivity extends Activity implements OnClickListener {private ImageView ivIcon; private EditText etUrl; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); ivIcon = (ImageView) findViewById (R. id. iv_icon); etUrl = (EditText) findViewById (R. id. et_url); Button btn = (Button) findViewById (R. id. btn_submit); btn. setOnClickListener (this) ;}@ Overridepublic void onClick (View v) {String url = etUrl. getText (). toString (); Bitmap bit = getImageFromNet (url); ivIcon. setImageBitmap (bit);} public Bitmap getImageFromNet (String url) {try {URL mUrl = new URL (url); // create a URL object HttpURLConnection conn = (HttpURLConnection) mUrl. openConnection (); conn. setRequestMethod ("GET"); conn. setConnectTimeout (10000); // sets the connection timeout value conn. setReadTimeout (5000); // set the read timeout value conn. connect (); int responseCode = conn. getResponseCode (); if (responseCode = 200) {InputStream is = conn. getInputStream (); Bitmap bitmap = BitmapFactory. decodeStream (is); Toast. makeText (this, "obtained successfully", 0 ). show (); return bitmap;} catch (Exception e) {e. printStackTrace ();} return null ;}}
3. Add Network Access Permissions
,