Android 网络编程--URL互联网资源

1.加入权限

 <uses-permission android:name="android.permission.INTERNET"/>

2.Layout设计

<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" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

 3.Code设计

public class MainActivity extends Activity {

	private Bitmap bitmap;
	private ImageView show;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				show.setImageBitmap(bitmap);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		show = (ImageView) this.findViewById(R.id.imageView);

		new Thread() {
			 
			@Override  
			public void run() {
			    super.run();  
				try {
					URL url = new URL(
							"http://a.hiphotos.baidu.com/image/h%3D220/sign=bd9eb2ea07087bf462ec50ebc2d2575e/d439b6003af33a87495b8dbbc35c10385343b559.jpg");
					InputStream inputStream = url.openStream();
					bitmap = BitmapFactory.decodeStream(inputStream);
					handler.sendEmptyMessage(1);
					inputStream.close();

				} catch (Exception e) {
					e.printStackTrace();
				}

			};

		}.start();
	}

}

 

你可能感兴趣的:(Android 网络编程--URL互联网资源)