• 爱情文章
  • 亲情文章
  • 友情文章
  • 生活随笔
  • 校园文章
  • 经典文章
  • 人生哲理
  • 励志文章
  • 搞笑文章
  • 心情日记
  • 英语文章
  • 范文大全
  • 作文大全
  • 新闻阅读
  • 当前位置: 山茶花美文网 > 作文大全 > 正文

    异步获取_Android开发之异步获取并下载网络资源

    时间:2020-05-27来源:山茶花美文网 本文已影响 山茶花美文网手机站

    1)从指定的URL获取对应的流

    既然要获取网络资源,那么首先得有个URL,那么这里我首先封装一个打开URL连接获取到的InputStream 流,这样一来无论是图片资源还是文本文件资源都可以使用该接口方法来获取流。

    该功能主要应用URLConnection和HttpURLConnection来实现,具体实现方案如下:

    复制代码

    private InputStream openHttpConnection(String urlString) throws IOException{

    InputStream in = null;

    int response = -1;

    URL url = new URL(urlString);

    URLConnection conn = url.openConnection();

    if(!(conn instanceof HttpURLConnection)){

    throw new IOException("It is not an HTTP connection");

    }

    try {

    HttpURLConnection httpConn = (HttpURLConnection) conn;

    httpConn.setAllowUserInteraction(false);

    httpConn.setInstanceFollowRedirects(true);

    httpConn.setRequestMethod("GET");

    httpConn.connect();

    response = httpConn.getResponseCode();

    if (response == HttpURLConnection.HTTP_OK) {

    in = httpConn.getInputStream();

    }

    } catch (Exception ex) {

    Log.v("Networking",ex.getLocalizedMessage());

    throw new IOException("Error connecting");

    }

    return in;

    }

    复制代码

    (2)封装了上面的获取流方法接口后,我们就可以利用上面封装的方法来获取并下载相应图片和文本文件内容了

    获取并下载图片资源方法:

    复制代码

    private Bitmap downloadImage(String url){

    Bitmap bitmap = null;

    InputStream in = null;

    try {

    in = openHttpConnection(url);

    bitmap = BitmapFactory.decodeStream(in);

    in.close();

    } catch (IOException e) {

    // TODO Auto-generated catch block

    Log.v("NetworkingActivity", e.getLocalizedMessage());

    }

    return bitmap;

    }

    复制代码

    获取并下载文本内容方法:

    复制代码

    private String downloadText(String url){

    int BUFFER_SIZE = 2000;

    InputStream is = null;

    try {

    is = openHttpConnection(url);

    } catch (IOException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    return "";

    }

    InputStreamReader isr = new InputStreamReader(is);

    int charRead;

    String str="";

    char[] inputBuffer = new char[BUFFER_SIZE];

    try {

    while((charRead=isr.read(inputBuffer))0){

    String readString = String.copyValueOf(inputBuffer, 0, charRead);

    str += readString;

    inputBuffer = new char[BUFFER_SIZE];

    }

    is.close();

    } catch (IOException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    return "";

    }

    return str;

    }

    复制代码

    (3)在获取下载图片资源和文本内容资源方法都完成后,现在就可以开始下载任务了,为了防止等待效应,一般采用异步任务来下载网络资源。

    对对应的下载资源任务封装各自的异步下载任务即可。下面就是实现异步下载任务的方案:

    异步下载图片任务:

    复制代码

    private class DownloadImageTask extends AsyncTask{

    long imagesCount = 0;

    ProgressBar progressBar;

    public DownloadImageTask(ProgressBar pBar){

    this.progressBar = pBar;

    }

    @Override

    protected Long doInBackground(String... urls) {

    // TODO Auto-generated method stub

    for(int i = 0; i urls.length;i++){

    Bitmap imageDownloaded = downloadImage(urls[i]);

    if(imageDownloaded!=null){

    imagesCount ++;

    publishProgress(imageDownloaded);

    try {

    Thread.sleep(300);

    } catch (InterruptedException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    }

    }

    }

    return imagesCount;

    }

    //display the image downloaded

    @Override

    protected void onProgressUpdate(Bitmap... bitmaps) {

    // TODO Auto-generated method stub

    ivImg.setImageBitmap(bitmaps[0]);

    progressBar.setProgress((int) imagesCount*10);

    }

    //when all the images have been downloaded

    @Override

    protected void onPostExecute(Long imageDownloaded) {

    // TODO Auto-generated method stub

    String str = "下载完成!一共下载了"+imagesCount +"张图片";

    Toast.makeText(getBaseContext(), str, Toast.LENGTH_SHORT).show();

    }

    }

    复制代码

    异步下载文本文件内容任务:

    复制代码

    private class DownloadTextTask extends AsyncTask{

    @Override

    protected void onPostExecute(String result) {

    // TODO Auto-generated method stub

    Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();

    }

    @Override

    protected String doInBackground(String... urls) {

    // TODO Auto-generated method stub

    return downloadText(urls[0]);

    }

    }

    复制代码

    这样一来,异步下载网络资源就完成了。

    下面为了读者方便测试,下面提供本文实例代码中的相关网络资源URL,以方便大家自己测试使用。其余非核心代码就不在贴出来,望读者见谅。

    复制代码

    //图片下载URLs

    private String[] mUrl =

    {

    "http://images.cnitblog.com/i/322919/201405/181111308592436.png",

    "http://images.cnitblog.com/i/322919/201405/181111385003770.png",

    "http://images.cnitblog.com/i/322919/201405/181111493901865.png",

    "http://images.cnitblog.com/i/322919/201405/181111550463327.png",

    "http://images.cnitblog.com/i/322919/201405/181117587961455.png",

    "http://images.cnitblog.com/i/322919/201405/181118041251414.png",

    "http://images.cnitblog.com/i/322919/201405/181119313754936.png",

    "http://images.cnitblog.com/i/322919/201405/181119357816682.png",

    "http://images.cnitblog.com/i/322919/201405/181119458753432.png",

    "http://images.cnitblog.com/i/322919/201405/181119499372608.png",

    "http://images.cnitblog.com/i/322919/201405/181120173901329.png",

    "http://images.cnitblog.com/i/322919/201405/181120244849561.png",

    "http://images.cnitblog.com/i/322919/201405/181120357812013.png",

    "http://images.cnitblog.com/i/322919/201405/181120398596959.png"

    };

    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    progressBar.setMax(mUrl.length*10);

    progressBar.setVisibility(View.VISIBLE);

    //异步下载图片任务

    DownloadImageTask task = new DownloadImageTask(progressBar);

    task.execute(mUrl);

    //文本文件URL

    String strUrl = "http://www.sogou.com/docs/about.htm";

    //异步下载文本文件内容任务

    new DownloadTextTask().execute(strUrl);

    • 异步获取_Android开发之异步获取并下载网络资源 相关文章:
    • 爱情文章
    • 亲情文章
    • 友情文章
    • 随笔
    • 哲理
    • 励志
    • 范文大全