我开发了一个简单的asynctask,可以从网站下载文件并显示它 有一种奇怪的行为:
ProgressDialog在下载开始时正确显示
正在将ProgressDialog从0%正确更新为100%,当下载完成后,它将消失,PDF文件将被打开。
ProgressDialog在下载开始时正确显示
ProgressDialog保持为0%,下载完成后消失,PDF文件正确打开。
可能是什么问题呢? (我使用的是Android 2.3.7)
谢谢!
public class TamTam extends Activity {
public ProgressDialog mProgressDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressDialog = new ProgressDialog(TamTam.this);
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
new DownloadFileAsync().execute("http://www.*******.com/file.pdf");
}
class DownloadFileAsync extends AsyncTask<String, Integer, String> {
String fileName;
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
@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();
fileName="output.pdf";
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(new File(
Environment.getExternalStorageDirectory()
+ "/" + fileName));
byte data[] = new byte[1024];
count = 0;
long total = 0;
while ((count = input.read(data)) > 0) {
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(Integer... progress) {
mProgressDialog.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String unused) {
mProgressDialog.dismiss();
showPdf(fileName);
}
}
public void showPdf(String fileName)
{
....
}
}
答案 0 :(得分:1)
正如迈克所说,问题在于这条线:
int lenghtOfFile = conexion.getContentLength();
问题是服务器没有提供内容长度标题。 使用HEAD请求,我让服务器回复正确的内容长度字段,否则该字段为空。要指定请求方法,我必须使用HttpURLConnection而不是URLConnection。
所以我改变了这个块
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
用这个
HttpURLConnection conexion2 = (HttpURLConnection) url.openConnection();
conexion2.setRequestMethod("HEAD");
int lenghtOfFile = conexion2.getContentLength();
URLConnection conexion = url.openConnection();
conexion.setDoOutput(true);
conexion.connect();
来源:
http://en.wikipedia.org/wiki/Chunked_transfer_encoding
Java URLConnection : how can I find out the size of a web file?