public class MainActivity extends AppCompatActivity {
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.iv);
}
public void onLoadClick(View v) {
imageView.setImageResource(R.mipmap.loading);
loadImage("https://i0.hdslb.com/bfs/archive/622017dd4b0140432962d3ce0c6db99d77d2e937.png");
}
private void loadImage(final String imgUrl) {
/**
* 1.找到图片的地址
* 2.根据图片的地址,将图片转化为可以加载的对象
* 3.通过ImageView来把对象给展示出来
*/
new Thread() {
@Override
public void run() {
final Message message = Message.obtain();
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
URL url = new URL(imgUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int code = connection.getResponseCode();
if (code == 200) {
//请求成功
inputStream = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
message.obj = bitmap;
message.what = 200;
} else {
//请求失败
message.what = code;
}
} catch (MalformedURLException e) {
e.printStackTrace();
message.what = -1;
} catch (IOException e) {
e.printStackTrace();
message.what = -1;
} finally {
//发送消息
handler.sendMessage(message);
if (connection != null) {
connection.disconnect();
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}.start();
}
private Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 200:
Bitmap bitmap = (Bitmap) msg.obj;
imageView.setImageBitmap(bitmap);
break;
default:
imageView.setImageResource(R.mipmap.loader_error);
break;
}
}
};
}
布局代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp"
android:orientation="vertical">
<Button
android:id="@+id/btn_load"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onLoadClick"
android:text="加载图片" />
<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>