package com.example.testapplication;
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.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class GetpngActivity extends AppCompatActivity {
// 第二步 主线程接收到子线程发送过来的消息进行处理显示
private ImageView main_iv_show;
private Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message message) {
if(message.what == 0x001){
Bitmap bm = (Bitmap) message.obj;
// ??
main_iv_show.setImageBitmap(bm);
}
return false;
}
});
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_getpng);
main_iv_show = (ImageView) findViewById(R.id.main_image_show);
}
// button 点击事件
public void getPic(View view){
String path = "https://img2.mukewang.com/5adfee7f0001cbb906000338-240-135.jpg";
// 创建一个线程对象
GetPicThread gpt = new GetPicThread(path,handler);
Thread t = new Thread(gpt);
t.start();
}
// 第一步 子线程去请求获取网络图片
// 获取网络的线程,耗时操作需要再子线程操作
public class GetPicThread implements Runnable{
private String path = null;
// handler 用于将数据送到主线程中
private Handler handler = null;
public GetPicThread(String path, Handler handler) {
this.path = path;
this.handler = handler;
}
@Override
public void run() {
HttpURLConnection conn = null;
InputStream is = null;
InputStreamReader istr = null;
BufferedReader br = null;
try {
// 1.定义艺哥URL对象
URL url = new URL(path);
// 2.通过url获取一个HttpURLConnerction();
conn = (HttpURLConnection) url.openConnection();
// 3.设置请求方式
conn.setRequestMethod("GET");
// 4.设置超时时间
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
// 获取到网络输入的字符流
is = conn.getInputStream();
// 借助位图工厂类的方法,将流转换为tu
Bitmap bm = BitmapFactory.decodeStream(is);
// 将获取的数据发送给主线程中去
Message message = handler.obtainMessage();
message.what = 0x0001;
message.obj = bm;
handler.sendMessage(message);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/main_btn"
android:onClick="getPic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="获取网络图片"/>
<ImageView
android:id="@+id/main_image_show"
android:layout_width="150dp"
android:layout_height="150dp" />
</LinearLayout>