Meanwhile AsyncTask can be used to deal with some of the more time-consuming background tasks, view the source code found inside the package is a Handler and thread pool, so you can help us deal with time-consuming task to update the UI.
The content on the use of AsyncTask to achieve complete Demo a simple loading progress on the picture to listen, of course, there are many listener implementation methods, there are many open-source image loading framework also implement this feature, this time on when including open ideas, can be considered together and review what we use AsyncTask it.
Demo Code
public class MainActivity extends AppCompatActivity {
private ProgressBar mProgressBar;
private ImageView mImageView;
private Button mButton;
private MyAsyncTask mTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressBar = findViewById(R.id.progressBar);
mImageView = findViewById(R.id.imageView);
mButton = findViewById(R.id.btn);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mTask = new MyAsyncTask(MainActivity.this);
String url = "http://wx1.sinaimg.cn/mw600/0076BSS5ly1gbophiekmuj30u0190aiq.jpg";
mTask.execute(url);
}
});
}
static class MyAsyncTask extends AsyncTask<String, Integer, Bitmap> {
private WeakReference<MainActivity> mWeakReference;
MyAsyncTask(MainActivity activity) {
mWeakReference = new WeakReference<>(activity);
}
//执行前的准备(UI线程)
@Override
protected void onPreExecute() {
super.onPreExecute();
}
//异步执行的代码(子线程)
@Override
protected Bitmap doInBackground(String... strings) {
String url = strings[0];
HttpURLConnection connection = null;
InputStream inputStream = null;
OutputStream outputStream = null;
File file;
Bitmap bitmap = null;
try {
connection = (HttpURLConnection) new URL(url).openConnection();
Log.i("kkk", "responseCode = " + connection.getResponseCode() + "\ncontentLength = " + connection.getContentLength());
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
return null;
//获取文件总长度
int totalLength = connection.getContentLength();
int currentLength = 0;
inputStream = connection.getInputStream();
file = new File(mWeakReference.get().getCacheDir().getAbsolutePath() + File.separator + url.substring(url.lastIndexOf("/")));
outputStream = new FileOutputStream(file);
byte[] bytes = new byte[1024 * 8];
int len;
int percent;
while ((len = inputStream.read(bytes)) != -1) {
currentLength += len;
percent = (int) ((float) currentLength / totalLength * 100);
//缓存到本地
outputStream.write(bytes, 0, len);
Log.i("kkk", "percent = " + percent);
publishProgress(percent);
}
//加载本地缓存的图片并返回
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (connection != null)
connection.disconnect();
if (inputStream != null)
inputStream.close();
if (outputStream != null)
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bitmap;
}
//执行进度(UI线程)
@Override
protected void onProgressUpdate(Integer... values) {
mWeakReference.get().mProgressBar.setProgress(values[0]);
}
//执行完成返回结果(UI线程)
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap == null)
return;
MainActivity activity = mWeakReference.get();
activity.mButton.setVisibility(View.GONE);
activity.mProgressBar.setVisibility(View.GONE);
activity.mImageView.setImageBitmap(bitmap);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mTask != null && !mTask.isCancelled()) {
mTask.cancel(true);
}
}
}
Complete results