Android AsyncTask 异步加载网络图片简单应用

释放双眼,带上耳机,听听看~!

这个是一个加载网络图片资源的小Demo可以很好地解释AsyncTask的工作流程

布局文件如下所示

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/asyimg"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="@+id/asyprog"
android:visibility="gone"
android:foregroundGravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>

MainActivity代码

 

package com.imooc.www.moocdemo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import java.io.BufferedInputStream;
import java.net.URL;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
/**
* Created by Administrator on 2016/5/12.
*/
public class AsyncImageActivity extends AppCompatActivity {
private ImageView mImageView;
private ProgressBar mProgressBar;
private static String URL = "https://img-my.csdn.net/uploads/201504/12/1428806103_9476.png";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.asyncimageactivity);
mImageView = (ImageView) findViewById(R.id.asyimg);
mProgressBar = (ProgressBar) findViewById(R.id.asyprog);
//设置传递进来的参数
new MyImageAsyncTask().execute(URL);
}
class MyImageAsyncTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
//获取传进来的参数 params为参数的意思 参数的个数不确定 params【0】表示获取第一个参数要注意一下
String url = params[0];
Bitmap bitmap = null;
URLConnection connection;
InputStream is;
try {
connection = new URL(url).openConnection();
is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
//通过decodeStream将输入流解析成bitmap
bitmap = BitmapFactory.decodeStream(bis);
//关闭输入流
is.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
//将bitmap作为返回值返回
return bitmap;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressBar.setVisibility(View.VISIBLE);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
mProgressBar.setVisibility(View.GONE);
mImageView.setImageBitmap(bitmap);
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}

人已赞赏
Android文章

Android ViewPager 的简单应用

2020-3-27 17:46:48

Android文章

Android开发AsyncTask 加载progressBar 的简单应用

2020-3-27 19:01:50

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索