我嘗試創建一個AsyncTask,它下載一個Zip文件並在通知中顯示下載進度。帶通知的AsyncTask
我打電話:
new MyAsyncTask.DownloadTask(context, position,list).execute(0);
其中提到這一點:
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.Button;
public class DownloadTask extends AsyncTask<Integer, Integer, Void> {
private NotificationHelper mNotificationHelper;
public int position;
public ArrayList<HashMap<String, String>> list;
public DownloadTask(Context context,int position, ArrayList<HashMap<String, String>> list) {
mNotificationHelper = new NotificationHelper(context);
this.position = position;
this.list = list;
}
protected void onPreExecute() {
mNotificationHelper.createNotification();
}
@SuppressLint("NewApi")
@Override
protected Void doInBackground(Integer... integers) {
int count;
try {
URL url = new URL("http://myurl/test.zip");
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
Log.d("Size: ", Integer.toString(lenghtOfFile));
InputStream input = new bufferedInputStream(url.openStream(),8192);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+ "/"+ list.get(position).get("Name") + ".zip");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) ((total * 100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
mNotificationHelper.progressUpdate(progress[0]);
}
@Override
protected void onPostExecute(Void result) {
mNotificationHelper.completed();
}
}
這似乎工作得很好,但是當我點擊我的按鈕運行的AsyncTask,所有的系統正在放緩,直到下載完成後才能使用平板電腦。 (當郵編是100mo時不是非常有用)。
另外,我想讓取消下載成爲可能,但是當我嘗試從我的主要活動(如類似這樣的事情:MyAsynctask.cancel(true);
)中執行應用程序崩潰時。所以我想知道是否有適當的方法來做到這一點(也許從通知給予最好的用戶體驗)。
編輯:
與滯後的問題就解決了,這要歸功於與更新時間不太重要的buptcoder:
while ((count = input.read(data)) != -1) {
total += count;
if ((count % 10) == 0) {
publishProgress((int) ((total * 100)/;lenghtOfFile));
}
output.write(data, 0, count);
}
我還在尋找一種方式來取消通知。
添加崩潰的logcat – Prachi 2013-05-03 09:36:02