android studio release,Android AsyncTask Download

 2023-11-22 阅读 18 评论 0

摘要: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
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"><Buttonandroid:id="@+id/execute"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="@string/download"/><Buttonandroid:id="@+id/cancel"android:layout_width="fill_parent"android:layout_height="wrap_content"android:enabled="false"android:visibility="gone"android:text="@string/cancel"/><ProgressBarandroid:id="@+id/progress_bar"android:layout_width="fill_parent"android:layout_height="wrap_content"android:progress="0"android:max="100"style="?android:attr/progressBarStyleHorizontal"/><TextViewandroid:id="@+id/txtResult"android:layout_width="fill_parent"android:textSize="20dp"android:layout_height="wrap_content"/><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:textSize="20dp"android:text="@string/doneList"/><ScrollViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"><TextViewandroid: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;@Overridepublic 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() {@Overridepublic 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() {@Overridepublic 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);}@Overridepublic 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;}@Overridepublic 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 SimplifiableIfStatementreturn super.onOptionsItemSelected(item);}private class MyTask extends AsyncTask<String, Integer, String> {//onPreExecute方法用于在執行后臺任務前做一些UI操作@Overrideprotected 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@Overrideprotected 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方法用于更新進度信息@Overrideprotected void onProgressUpdate(Integer... progresses) {//Log.i(TAG, "onProgressUpdate(Progress... progresses) called");progressBar.setProgress(progresses[0]);txtResult.setText("[" + this.fileName + "]" + "=>[下載中..." + progresses[0] + "%]\n");}//onPostExecute方法用于在執行完后臺任務后更新UI,顯示結果@Overrideprotected 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@Overrideprotected void onCancelled() {//Log.i(TAG, "onCancelled() called");txtResult.setText("cancelled");progressBar.setProgress(0);execute.setEnabled(true);cancel.setEnabled(false);}}
}

?Ref:詳解Android中AsyncTask的使用

轉載于:https://www.cnblogs.com/ncore/p/4381384.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/184899.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息