//网络请求操作耗时,一般不要放在主线程中,否则主线程阻塞,UI停止刷新
//应用无法响应用户操作,主线程又称为UI线程,只有在主线程中才能刷新UI消息队列机制
主线程创建时,系统会同时创建消息队列对象(MessageQueue)和消息轮询器对象
(Looper)
轮询器的作用:就是不停的检测消息队列中是否有(Message)
消息队列一旦有消息,轮询器会把消息对象传给消息处理器(Handler),处理器
会调用handlerMessage方法来处理这条消息,handlerMessage方法会运行在
主线程中,所以可以刷新UI,只要消息队列有消息,handlerMessage就会调用
子线程如果需要刷新UI,只需要往消息队列发送一条消息即可。
子线程使用处理器对象的sendMessage()方法发送消息。
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap((Bitmap) msg.obj);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
}
public void dianji(View view) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
//图片的网址
String path = "http://localhost:8999/72.jpg";
try {
//把网址封装成一个url对象
URL url = new URL(path);
//获取客户端和服务器的连接对象,这时候还没有建立起连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//对连接对象进行初始化
//设置请求方法,注意大写
conn.setRequestMethod("GET");
//设置连接超时
//conn.setConnectTimeout(5000);
//设置读取超时
//conn.setReadTimeout(5000);
//发送请求与服务器进行连接
conn.connect();
//获取响应码
if (conn.getResponseCode() == 200) {
//请求成功
//获取服务器响应头中的流,流里的数据就是客户端请求的数据
InputStream is = conn.getInputStream();
//读取出流里的数据并形成图片
Bitmap bitmap = BitmapFactory.decodeStream(is);
Message message = new Message();
message.obj = bitmap;
handler.sendMessage(message);
} else {
Toast.makeText(getApplicationContext(), "请求失败", Toast.LENGTH_SHORT).show();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
//不要忘记加入网络权限