0
我已經使用以下類下載文件並將其保存到SD卡。使用Asynctask下載並保存文件無法正常工作
class DownloadFileAsync extends AsyncTask<String, String, String> {
@SuppressWarnings("deprecation")
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"PurchasedFrames/"+filename);
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) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
File file = new File("/sdcard/PurchasedFrames/", filename);
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
ImageView frame = (ImageView) findViewById(R.id.frame);
frame.setImageBitmap(myBitmap);
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
對話框方法
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
我用上面的代碼問題,進度會出現,但它沒有完成消失,沒有下載發生。我無法注意到任何logcat錯誤或任何其他調試錯誤。任何人都可以告訴可以發生什麼事情或如何克服這個問題?
您還沒有打印任何東西取代您的異常塊在'doInBackground'的'catch'塊中。在'catch'塊中寫入'e.printStrackTrace()'並再次檢查。 – Apoorv
您可能會在您的try塊中收到異常。把一個println放入你的catch塊並檢查 – SoulRayder
這只是一個猜測,但是conexion.connect();應該關閉嗎?如果您讓我們知道發生了哪些異常(來自logcat),我們可能能夠查明問題 – SoulRayder