• android 多线程 AsyncTask 下载图片


    AsyncTask 下载图片

    package com.test.network;
    
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.AsyncTask;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.ImageView;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.Objects;
    
    /**
     * AsyncTask 实现图片下载、显示
     */
    public class AsyncDownLoadActivity extends AppCompatActivity {
    
        private String urlPath = "http://img4.imgtn.bdimg.com/it/u=3340865222,3464212128&fm=21&gp=0.jpg";
        private ImageView imageView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_async_down_load);
            imageView = (ImageView) findViewById(R.id.imageView);
            new AsynPicTask().execute(imageView, urlPath);
        }
    
        class AsynPicTask extends AsyncTask<Object, Object, Bitmap> {
    
            private ImageView imageView;
    
            protected void onPreExecute() {
            }
    
            //执行耗时操作
            @Override
            protected Bitmap doInBackground(Object... params) {
                imageView = (ImageView) params[0];
                Bitmap bitmap = null;
                try {
                    URL url = new URL((String) params[1]);
                    URLConnection urlConnection = url.openConnection();
                    urlConnection.setConnectTimeout(3000);
                    urlConnection.connect();
    
                    InputStream inputStream = urlConnection.getInputStream();
    
                    bitmap = BitmapFactory.decodeStream(inputStream);
                    inputStream.close();
    
    
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return bitmap;
            }
    
            protected void onProgressUpdate(Object... values) {
            }
    
            //耗时操作返回结果
            protected void onPostExecute(Bitmap result) {
                imageView.setImageBitmap(result);
            }
    
    
        }
    }
  • 相关阅读:
    python3 crypto winrandom import error
    Flask-Babel 中文支持(zh-CN和zh-Hans-CN)
    pip 安装psycopg的错误
    Aapache status / apache2ctl status 总是403
    为什么你还在用嵌入式的方式来使用mod_wsgi?
    Git中当add错误的时候怎么办?
    Python 内置彩蛋
    本人AI知识体系导航
    本人SW知识体系导航
    SSH密钥对登录的原理和实践
  • 原文地址:https://www.cnblogs.com/newlangwen/p/5394270.html
Copyright © 2020-2023  润新知