【发布时间】:2011-07-12 01:33:49
【问题描述】:
我正在尝试使用 AsyncTask 在后台将 mp 文件下载到模拟器中,它可以正常工作.. 但在 divice 中它不显示 progressbar
这个问题是由于当我运行这段代码时
int lenghtOfFile = c.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
这给了我-1 为什么会发生这种情况?我的代码是
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
// mp3load();
int len1 = 0;
int count;
try {
URL url = new URL(GlobalVariable.Getstr());
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lenghtOfFile = c.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
Log.v(LOG_TAG, "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
// String fileName = "workTest.mp3";
String fileName = GlobalVariable.Getstrpath().toString();
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
long total = 0;
while ((count = is.read(buffer)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// fos.write(buffer, 0, len1);
fos.write(buffer, 0, count);
}
fos.close();
is.close();
} catch (IOException e) {
Log.d(LOG_TAG, "Error: " + e);
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
refreshList();
Toast.makeText(
FindFilesByType.this,
"Downloading of " + GlobalVariable.Getstrpath()
+ " complete.", Toast.LENGTH_LONG).show();
// Intent i = new Intent(FindFilesByType.this, SongList.class);
// finish();
// startActivity(i);
try{
Intent i = new Intent(FindFilesByType.this, SongList.class);
finish();
startActivity(i);}catch (Exception e) {
// TODO: handle exception
}
}
}
整个代码适用于模拟器
但它总是不显示我的进度,但下载成功
感谢Pragna
【问题讨论】:
标签: android android-asynctask httpurlconnection