1. 程式人生 > >android 獲取網路圖片並在Imageview上顯示

android 獲取網路圖片並在Imageview上顯示


這個是我使用的圖片。。。http://imgstore04.cdn.sogou.com/app/a/100520024/877e990117d6a7ebc68f46c5e76fc47a

佈局中宣告一個ImageView控制元件,和一個button,控制載入圖片,新建一個執行緒進行網路連線處理

package com.example.urlimage;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {

	//宣告地址
	private Button btn;
	private ImageView img;
	private String url = "http://imgstore04.cdn.sogou.com/app/a/100520024/877e990117d6a7ebc68f46c5e76fc47a";

	//在訊息佇列中實現對控制元件的更改
	private Handler handle = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				System.out.println("111");
				Bitmap bmp=(Bitmap)msg.obj;
				img.setImageBitmap(bmp);
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		btn = (Button) findViewById(R.id.btn);
		img = (ImageView) findViewById(R.id.img);

		btn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				//新建執行緒載入圖片資訊,傳送到訊息佇列中
				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						Bitmap bmp = getURLimage(url);
						Message msg = new Message();
						msg.what = 0;
						msg.obj = bmp;
						System.out.println("000");
						handle.sendMessage(msg);
					}
				}).start();
			}
		});
	}

	//載入圖片
	public Bitmap getURLimage(String url) {
		Bitmap bmp = null;
		try {
			URL myurl = new URL(url);
			// 獲得連線
			HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();
			conn.setConnectTimeout(6000);//設定超時
			conn.setDoInput(true);
			conn.setUseCaches(false);//不快取
			conn.connect();
			InputStream is = conn.getInputStream();//獲得圖片的資料流
			bmp = BitmapFactory.decodeStream(is);
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bmp;
	}
}

最後在manifest檔案上面設定<uses-permission android:name="android.permission.INTERNET" />上網許可權