时间:2020-12-30 13:55:52 | 栏目:Android代码 | 点击:次
Android下载网络图片的流程是:
发送网络请求->将图片以流的形式下载下来->将流转换为Bitmap并赋给ImageView控件。
注意点
设计思路
1.网络请求:该例中需要下载的文件类型是图片类型,可以将网络请求获取的数据类型转换为Bitmap已供ImageView直接使用,但是一个合理的网络请求类的设计是将下载的数据类型转换为最基本的InputStream,这样不管是下载图片,音频,文本还是视频,都可以将结果抛出去让上层的逻辑来处理。
2.异步请求:下载图片,网络下载属于耗时操作,所以需要封装一个AsyncTask来处理网络请求,该请求继承自Runnable接口。
3.异步回调:前台需要通过回调的方式来得到图片源,并将该图片源赋值给ImageView.
相关代码
NetService:网络请求服务类
public class NetService { public static InputStream getInputStreamByUrl(String address){ URL url = null; HttpURLConnection urlConnection = null; try { url = new URL(address); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(2 * 1000); urlConnection.setRequestMethod("GET"); return urlConnection.getInputStream(); } catch (IOException e) { e.printStackTrace(); } return null; } }
NetServiceTask:AsyncTask类
import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import java.io.BufferedInputStream; import java.io.InputStream; public class NetServiceTask extends AsyncTask public NetServiceTask(String address, URLPostHandler urlPostHandler) { this.address=address; this.urlPostHandler=urlPostHandler; } /** * 表示任务执行之前的操作 */ @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); } /** * 主要是完成耗时的操作 */ @Override protected Bitmap doInBackground(String... arg0) { InputStream inputStream=NetService.getInputStreamByUrl(arg0[0]); if(inputStream!=null){ return BitmapFactory.decodeStream(new BufferedInputStream(inputStream)); } return null; } /** * 主要是更新UI的操作 */ @Override protected void onPostExecute(Bitmap result) { // TODO Auto-generated method stub super.onPostExecute(result); if(this.urlPostHandler!=null&&result!=null){ this.urlPostHandler.PostHandler(result); } } @Override public void run() { execute(this.address); } }
URLPostHandler:回调接口
public interface URLPostHandler { void PostHandler(Bitmap bitmap); }
前台请求图片并显示到ImageView
public class MainActivity extends AppCompatActivity { Button buttonDownload; ImageView imageViewImg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonDownload = (Button) findViewById(R.id.buttonDownload); imageViewImg = (ImageView) findViewById(R.id.imageViewImg); buttonDownload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String address = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1490783056273&di=6160d101d31dcf5f44b443ad9c5b2648&imgtype=0&src=http%3A%2F%2Fimg.sc115.com%2Fuploads%2Fallimg%2F110626%2F2011062622383898.jpg"; NetServiceTask netServerTask= new NetServiceTask(address,new URLPostHandler() { @Override public void PostHandler(Bitmap bitmap) { imageViewImg.setImageBitmap(bitmap); } }); Thread thread=new Thread(netServerTask); thread.start(); } }); } }