首页 > 代码库 > 安卓学习-界面-事件-AsyncTask

安卓学习-界面-事件-AsyncTask

异步任务Asynctask完成一个下载

 

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"    tools:context="${relativePackage}.${activityClass}" >    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true"        android:layout_marginLeft="23dp"        android:layout_marginTop="14dp"        android:text="开始下载" />    <EditText        android:id="@+id/editText1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignLeft="@+id/button1"        android:layout_alignParentBottom="true"        android:layout_alignParentRight="true"        android:layout_below="@+id/button1"        android:layout_marginTop="45dp"        android:ems="10"        android:inputType="textMultiLine" >        <requestFocus />    </EditText></RelativeLayout>
View Code

MainActivity.java

public class MainActivity extends Activity {    EditText editText1;    Button btn1;        @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        editText1=(EditText)findViewById(R.id.editText1);        btn1=(Button)findViewById(R.id.button1);        btn1.setOnClickListener(new OnClickListener() {                        @Override            public void onClick(View v) {                MyDown down=new MyDown(MainActivity.this);                try {                    down.execute(new URL("http://w.x.baidu.com/alading/anquan_soft_down_normal/12350"));                } catch (MalformedURLException e) {                    // TODO 自动生成的 catch 块                    e.printStackTrace();                }                            }        });    }            class MyDown extends AsyncTask<URL, Integer, String>{        //下载进度        ProgressDialog p;        //总下载量        int totalSize=0;        //当前下载        int downloadSzie=0;        Context context;        //下载开始时间        Calendar date_s=Calendar.getInstance();        //下载结束时间        Calendar date_e;        public MyDown(Context context){            this.context=context;        }                @Override        protected void onPreExecute() {             p=new ProgressDialog(context);             p.setMax(0);             p.setTitle("任务执行中");             p.setMessage("任务执行完成比,请等待......");             p.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);             p.setCancelable(false);             p.setIndeterminate(false);             p.show();        }                @Override        protected String doInBackground(URL... params) {            StringBuffer str=new StringBuffer();            try {                HttpURLConnection http=(HttpURLConnection)params[0].openConnection();                //获取总下载量                totalSize=http.getContentLength();                InputStream in=http.getInputStream();                                byte[] buffer =new byte[1024];                int readSize=0;                while ((readSize=in.read(buffer))!=-1){                    date_e=Calendar.getInstance();                    //计算下载的总时间,主要是用于计算  K/S                    int a=(int)(date_e.getTimeInMillis()-date_s.getTimeInMillis())/1000;                                        //总下载数                    downloadSzie =downloadSzie +readSize;                    //刷新UI                    publishProgress(downloadSzie,totalSize,a);                }                return str.toString();                            } catch (Exception e) {                // TODO 自动生成的 catch 块                e.printStackTrace();            }            return null;        }                protected void onPostExecute(String result) {            editText1.setText("下载完成");            p.dismiss();        }                @Override        protected void onProgressUpdate(Integer... values) {            p.setProgress(values[0]/1024);            p.setMax(values[1]/1024);            int sed=0;            if(values[2]==0) sed=1;else sed=values[0]/1024/values[2];            p.setMessage("任务执行完成比,请等待......\n 速度 "+sed+" K/S");        }            }}
View Code

 

安卓学习-界面-事件-AsyncTask