Android AsyncTask Download

來源:互聯網
上載者:User

標籤:

AndroidManifest.xml
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
activity_download_file.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent">    <Button        android:id="@+id/execute"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/download"/>    <Button        android:id="@+id/cancel"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:enabled="false"        android:visibility="gone"        android:text="@string/cancel"/>    <ProgressBar        android:id="@+id/progress_bar"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:progress="0"        android:max="100"        style="?android:attr/progressBarStyleHorizontal"/>    <TextView        android:id="@+id/txtResult"        android:layout_width="fill_parent"        android:textSize="20dp"        android:layout_height="wrap_content"/>    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:textSize="20dp"        android:text="@string/doneList"/>    <ScrollView        android:layout_width="fill_parent"        android:layout_height="wrap_content">        <TextView            android:id="@+id/txtDoneList"            android:textSize="20dp"            android:layout_width="fill_parent"            android:layout_height="wrap_content" />    </ScrollView></LinearLayout> 
DownloadFileActivity
package com.buzz.activity;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import android.support.v7.app.ActionBarActivity;import android.os.AsyncTask;import android.os.Bundle;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView;import com.buzz.models.action;import com.buzz.utils.GlobalConst;public class DownloadFileActivity extends ActionBarActivity {    static final String TAG = "ASYNC_TASK";    Button execute;    Button cancel;    ProgressBar progressBar;    TextView txtResult;    TextView txtDoneList;    Map<String, MyTask> taskList;    MyTask mTask;    MyApplication myApp;    int fileCounter;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_download_file);        myApp = (MyApplication) getApplication();        taskList = new HashMap<String, MyTask>();        execute = (Button) findViewById(R.id.execute);        execute.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                txtDoneList.setText("");                taskList.clear();                //注意每次需new一個執行個體,建立的任務只能執行一次,否則會出現異常                for (List<action> acList : myApp.actionList.values()) {                    for (action ac : acList) {                        taskList.put(ac.getServerpath(), new MyTask(ac.getClientpath(), ac.getFilename()));                    }                }                for (Map.Entry<String, MyTask> entry : taskList.entrySet()) {                    entry.getValue().execute(entry.getKey());                }                execute.setEnabled(false);                cancel.setEnabled(true);            }        });        cancel = (Button) findViewById(R.id.cancel);        cancel.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //取消一個正在執行的任務,onCancelled方法將會被調用                mTask.cancel(true);            }        });        progressBar = (ProgressBar) findViewById(R.id.progress_bar);        txtResult = (TextView) findViewById(R.id.txtResult);        txtDoneList = (TextView) findViewById(R.id.txtDoneList);    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_download_file, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        //noinspection SimplifiableIfStatement        return super.onOptionsItemSelected(item);    }    private class MyTask extends AsyncTask<String, Integer, String> {        //onPreExecute方法用於在執行背景工作前做一些UI操作        @Override        protected void onPreExecute() {            //Log.i(TAG, "onPreExecute() called");            txtResult.setText("準備下載...\n");        }        private String clientPath;        private String fileName;        protected MyTask(String clientPath, String fileName) {            this.clientPath = clientPath;            this.fileName = fileName;        }        //doInBackground方法內部執行背景工作,不可在此方法內修改UI        @Override        protected String doInBackground(String... params) {            //Log.i(TAG, "doInBackground(Params... params) called");            try {                HttpClient client = new DefaultHttpClient();                HttpGet get = new HttpGet(params[0]);                HttpResponse response = client.execute(get);                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {                    HttpEntity entity = response.getEntity();                    InputStream is = entity.getContent();                    long total = entity.getContentLength();                    ByteArrayOutputStream baos = new ByteArrayOutputStream();                    byte[] buf = new byte[1024];                    int count = 0;                    int length = -1;                    while ((length = is.read(buf)) != -1) {                        baos.write(buf, 0, length);                        count += length;                        //調用publishProgress公布進度,最後onProgressUpdate方法將被執行                        publishProgress((int) ((count / (float) total) * 100));                        //為了示範進度,休眠500毫秒                        //Thread.sleep(500);                    }                    //儲存檔案                    String filePath = GlobalConst.PATH_SDCARD + this.clientPath;                    String fileName = this.fileName;                    String saveTo = filePath + fileName;                    File file = new File(filePath);                    file.mkdirs();                    file = null;                    file = new File(saveTo);                    file.createNewFile();                    OutputStream outputStream = new FileOutputStream(file);                    outputStream.write(baos.toByteArray());                    baos.close();                    baos.flush();                    outputStream.close();                    outputStream.flush();                    file = null;                    return "[" + this.fileName + "]" + "=>[下載完成]\n";                }            } catch (Exception e) {                //Log.i(TAG, e.getMessage());            }            return null;        }        //onProgressUpdate方法用於更新進度資訊        @Override        protected void onProgressUpdate(Integer... progresses) {            //Log.i(TAG, "onProgressUpdate(Progress... progresses) called");            progressBar.setProgress(progresses[0]);            txtResult.setText("[" + this.fileName + "]" + "=>[下載中..." + progresses[0] + "%]\n");        }        //onPostExecute方法用於在執行完背景工作後更新UI,顯示結果        @Override        protected void onPostExecute(String result) {            //Log.i(TAG, "onPostExecute(Result result) called");            txtResult.setText(result);            txtDoneList.append(result);            fileCounter++;            if (fileCounter == taskList.size()) {                execute.setEnabled(true);                cancel.setEnabled(false);            }        }        //onCancelled方法用於在取消執行中的任務時更改UI        @Override        protected void onCancelled() {            //Log.i(TAG, "onCancelled() called");            txtResult.setText("cancelled");            progressBar.setProgress(0);            execute.setEnabled(true);            cancel.setEnabled(false);        }    }}

 Ref:詳解Android中AsyncTask的使用

Android AsyncTask Download

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.