android studio 异步加载网站上的图片,模拟下载进度条
时间: 2023-11-07 08:49:22 浏览: 92
在 Android Studio 中,可以使用 AsyncTask 来实现异步加载网站上的图片,并模拟下载进度条。下面是一个简单的示例代码:
```java
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
progressBar = findViewById(R.id.progressBar);
new DownloadImageTask().execute("https://example.com/image.jpg");
}
private class DownloadImageTask extends AsyncTask<String, Integer, Bitmap> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setProgress(0);
}
@Override
protected Bitmap doInBackground(String... urls) {
String url = urls[0];
Bitmap bitmap = null;
try {
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.setDoInput(true);
conn.connect();
int totalSize = conn.getContentLength();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 8192);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
int downloadedSize = 0;
while ((len = bis.read(buffer)) != -1) {
baos.write(buffer, 0, len);
downloadedSize += len;
publishProgress((int) ((downloadedSize / (float) totalSize) * 100));
}
bitmap = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.size());
baos.flush();
baos.close();
bis.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
imageView.setImageBitmap(result);
progressBar.setVisibility(View.GONE);
}
}
}
```
在这个示例中,我们在主线程中调用 `new DownloadImageTask().execute(url)` 来开始异步加载图片。`DownloadImageTask` 继承自 `AsyncTask` 类,实现了图片的下载和进度条的更新。在 `doInBackground` 方法中,我们使用 `HttpURLConnection` 来下载图片,并在下载过程中使用 `publishProgress` 方法来更新进度条。在 `onPostExecute` 方法中,我们将下载完成的图片设置到 ImageView 中,并将进度条隐藏。
阅读全文