Android前端开发15:显示网络图片

占用主线程的做法(不推荐)

需要在onCreate()加入解除限制的代码

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

完整代码

package com.example.webimageview;

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.StrictMode;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private ImageView iv;
	private EditText et;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		iv = (ImageView) findViewById(R.id.iv);
		et = (EditText) findViewById(R.id.et);
		// 解除主线程不能访问网络的限制
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
	}

	public void ShowImage(View view) {
		String path = et.getText().toString().trim();
		if (TextUtils.isEmpty(path)) {
			Toast.makeText(this, "路径不能为空", Toast.LENGTH_SHORT).show();
		} else {
			// 连接服务器get图片
			try {
				URL url = new URL(path);
				// 根据url发送http请求
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				// 设置请求方式
				conn.setRequestMethod("GET");
				// 设置最大等待时间
				conn.setConnectTimeout(8 * 1000);
				conn.setReadTimeout(8 * 1000);
				// 设置浏览器信息
				conn.setRequestProperty("User-Agent",
						"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36");
				// 得到服务器返回的响应码
				int code = conn.getResponseCode();
				if (code == 200) {
					InputStream is = conn.getInputStream();
					Bitmap image = BitmapFactory.decodeStream(is);
					iv.setImageBitmap(image);
				} else {
					Toast.makeText(this, "图片请求失败", Toast.LENGTH_SHORT).show();
				}

			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(this, "获取图片失败", Toast.LENGTH_SHORT).show();
			}
		}
	}
}

创建网络子线程(推荐)

只有主线程能刷新应用UI,用Hander实现子线程请求主线程刷新UI

package com.example.webimageview;

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.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
	public final static int CHANGE_UI = 0;
	public final static int SHOW_MSG = 1;
	private ImageView iv;
	private EditText et;
	// 主线程创建消息处理器
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case CHANGE_UI:
				iv.setImageBitmap((Bitmap) msg.obj);
				break;
			case SHOW_MSG:
				Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		iv = (ImageView) findViewById(R.id.iv);
		et = (EditText) findViewById(R.id.et);
	}

	public void ShowImage(View view) {
		final String path = et.getText().toString().trim();
		if (TextUtils.isEmpty(path)) {
			Toast.makeText(this, "路径不能为空", Toast.LENGTH_SHORT).show();
		} else {
			new Thread() {
				public void run() {
					// 连接服务器get图片
					try {
						URL url = new URL(path);
						// 根据url发送http请求
						HttpURLConnection conn = (HttpURLConnection) url.openConnection();
						// 设置请求方式
						conn.setRequestMethod("GET");
						conn.setConnectTimeout(20000);
						conn.setRequestProperty("User-Agent",
								"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36");
						// 得到服务器返回的响应码
						int code = conn.getResponseCode();
						if (code == 200) {
							InputStream is = conn.getInputStream();
							Bitmap image = BitmapFactory.decodeStream(is);
							// 子线程发送图像消息
							Message msg = new Message();
							msg.what = CHANGE_UI;
							msg.obj = image;
							handler.sendMessage(msg);
						} else {
							//子线程发送文本提示消息
							Message msg = new Message();
							msg.what = SHOW_MSG;
							msg.obj = "图片请求失败";
							handler.sendMessage(msg);
						}

					} catch (Exception e) {
						e.printStackTrace();
						Message msg = new Message();
						msg.what = SHOW_MSG;
						msg.obj = "获取图片失败";
						handler.sendMessage(msg);
					}
				}
			}.start();

		}
	}
}

你可能感兴趣的:(Android)