我正在使用 AsyncTask 从 Android 中的 URL 下载文件。这是在后台下载文件的类:
//-----------------------------ASYNC DOWNLOADER--------------------------------
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
@SuppressWarnings("deprecation")
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
//TODO Zustzinfos für alle Methoden hinzufügen
/**
* This method is called for executing the background task in the AsyncTask.
* For this tutorial we are only sleeping the thread for the number of
* seconds passed as parameter of the function.
*
* @param numSeconds: life of the task
* @return the result of the background task
*/
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/"+Name+".xml");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("ASYNC",e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
@SuppressWarnings("deprecation")
@Override
protected void onPostExecute(String error) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
String xmlPath = Environment.getExternalStorageDirectory().toString() + "/"+Name+".xml";
Log.d("XMLDOWNLOADPATH", xmlPath);
Log.d("DOWNLOADXML","End Download XML file");
}
}
我希望能够在我的主要活动(异步类是主要活动的内部类)中识别是否存在异常并在对话框或 Toast 中显示错误消息。
我试图从 to 返回值doInBackground()
并将onPostExecute()
此字符串写入全局字符串变量,如下所示:
protected String doInBackground(String... f_url) {
String error = null;
try {
}
catch(Exception e){
error = e.toString();
}
return error;
@Override
protected void onPostExecute(String error) {
globalStringvariable = error;
}
但这不能正常工作,对话框并不总是显示异常消息。这是解决我的问题的最佳方法吗?