- 1,activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressBar1"
android:visibility="gone"
style="?android:attr/progressBarStyleLarge"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
- MainActivity.java
package com.example.flanwu.expriment_two;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import java.net.URL;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
private ImageView mImageView = null;
private ProgressBar mProgressBar = null;
private String URLs = "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1591194216,3468862819&fm=26&gp=0.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
//实例化控件
this.mImageView = (ImageView)findViewById(R.id.imageView1);
this.mProgressBar = (ProgressBar)findViewById(R.id.progressBar1);
//实例化异步任务
ImageDownloadTask task = new ImageDownloadTask();
// 执行异步任务
task.execute(URLs);
}
class ImageDownloadTask extends AsyncTask<String, Void, Bitmap>{
@Override
protected Bitmap doInBackground(String... params){
Bitmap bitmap = null;
String url = params[0];
URLConnection connection;
InputStream is;
try{
connection = new URL(url).openConnection();
is = connection.getInputStream(); //获取输入流
BufferedInputStream buf = new BufferedInputStream(is);
bitmap = BitmapFactory.decodeStream(buf);
is.close();
buf.close();
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPreExecute(){
// 显示等待圆环
mProgressBar.setVisibility(View.VISIBLE);
}
@Override
protected void onPostExecute(Bitmap result){
// 下载完毕,隐藏等待圆环
mProgressBar.setVisibility(View.GONE);
mImageView.setImageBitmap(result);
}
}
}
结果