码迷,mamicode.com
首页 > 其他好文 > 详细

asyncTask异步任务:从网络下载图片

时间:2014-07-25 02:19:14      阅读:297      评论:0      收藏:0      [点我收藏+]

标签:android   style   blog   http   java   color   使用   os   

【关键字】:3个参数,4个步骤

第一步:表示任务执行前的操作

第二步:主要完成耗时操作

第三步:主要是更新UI操作

第四步:产生最终结果

以下实例中代表的含义为:

第一步:显示进度条

第二步:(此任务必不可少)在后台执行任务,将进度值传给第三步,将结果传给第四步;

第三步:进度值更新

第四步:产生最终结果

1、添加网络授权:

因为手机默认不能访问网络,所以首先要在清单文件 AndroidManifest.xml中添加网络授权。

方法如下:

打开AndroidManifest.xml文件,点击"Permissions"按钮,然后点击“Add”:

bubuko.com,布布扣

弹出对话框后,选择最后一项:Users Permission:

bubuko.com,布布扣

接着选择其中的Internet选项:

bubuko.com,布布扣

按Ctrl+S保存即可。

紧接着,我们在清单文件中就能看到对应自动生成的代码:

bubuko.com,布布扣

【实例】从网络下载图片,弹出对话框,但不显示进度条:

完整版代码如下:

activity_main.xml的代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="136dp"
        android:text="下载网络图片" />
</RelativeLayout>

MainActivity.java的代码:

package com.example.downloadimage01;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
    private ImageView imageView ;
    private Button button ;   
    private ProgressDialog dialog ;
    //来自网络的图片
    private String image_path = "http://imgsrc.baidu.com/forum/pic/item/7c1ed21b0ef41bd51a5ac36451da81cb39db3d10.jpg" ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //添加弹出的对话框
        dialog = new ProgressDialog(this) ;
        dialog.setTitle("提示") ;
        dialog.setMessage("正在下载图片,请稍后···") ;
        
        imageView = (ImageView)findViewById(R.id.imageView1) ;
        button = (Button)findViewById(R.id.button1) ;
        button.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
            //点击按钮时,执行异步任务的操作
                new DownTask().execute(image_path) ;
            }
        }) ;   //注意,这个地方的分号容易遗忘
    }
    /* 
     * 异步任务执行网络下载图片
     * */
    public class DownTask extends AsyncTask<String, Void, Bitmap> {
    //上面的方法中,第一个参数:网络图片的路径,第二个参数的包装类:进度的刻度,第三个参数:任务执行的返回结果
        @Override
        //在界面上显示进度条
        protected void onPreExecute() {
            dialog.show() ;
        };
        protected Bitmap doInBackground(String... params) {  //三个点,代表可变参数
            //使用网络链接类HttpClient类完成对网络数据的提取
            HttpClient httpClient = new DefaultHttpClient() ;
            HttpGet httpget = new HttpGet(params[0]) ;
            Bitmap bitmap = null ;
            try {
                HttpResponse httpResponse = httpClient.execute(httpget) ;
                if(httpResponse.getStatusLine().getStatusCode()==200){
                    HttpEntity httpEntity = httpResponse.getEntity() ;
                    byte[] data = EntityUtils.toByteArray(httpEntity);
                    bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                }
            }  catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return bitmap;
        }
            //主要是更新UI
            @Override
            protected void onPostExecute(Bitmap result) { 
                super.onPostExecute(result);
                imageView.setImageBitmap(result) ;//更新UI
                dialog.dismiss() ;                
            }        
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}

运行后,点击按钮,显示结果如下:
bubuko.com,布布扣

bubuko.com,布布扣

asyncTask异步任务:从网络下载图片,布布扣,bubuko.com

asyncTask异步任务:从网络下载图片

标签:android   style   blog   http   java   color   使用   os   

原文地址:http://www.cnblogs.com/smyhvae/p/3866570.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!