我正在尝试通过此代码下载一些xml文件。 当网络可用时,一切正常。当网络根本没有时,我已经处理了这个问题。但现在面临的问题是,当网络速度缓慢时,下载不会超时。
我认为超时完全不起作用。如何让它发挥作用?
URL mUrl = new URL(url[i]);
URLConnection conexion = mUrl.openConnection();
response[i] = new DownloadResponse();
response[i].setSuccessful(false);
conexion.connect();
conexion.setConnectTimeout(10000);
// this will be useful so that you can show a typical 0-100% progress bar
ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
if (outputFile != null) { // one output file specified in constructor
output = new BufferedOutputStream(new FileOutputStream(
outputFile));
} else if (outputFiles != null) { // an array of output files specified
output = new BufferedOutputStream(new FileOutputStream(
outputFiles[i]));
} else {// no output file specified
output = new BufferedOutputStream(outBytes);
}
InputStream input = new BufferedInputStream(mUrl.openStream());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
response[i].setSuccessful(true);
response[i].count = i;
response[i].setResponseText(outBytes.toString());
if (total < 32 && outBytes.toString().indexOf("Invalid") < -1){
response[i].setSuccessful(false);
}
output.close();
input.close();
publishProgress(response[i]);
答案 0 :(得分:1)
在onclick whendownload按钮中
在班级boolean b = true;
count_Timer = new CountDownTimer(20000, 1000) {
@Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
@Override
public void onFinish() {
b = false;
pd.dismiss();
dialog.dismiss();
AlertDialog.Builder builder1 = new AlertDialog.Builder(
AppSetting.this);
builder1.setTitle("appname");
builder1.setMessage("You can't Continue because internet is Very slow.");
builder1.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
}
});
builder1.show();
}
};
开始下载任务
count_Timer.start();
在doinbackground的最后一行
count_Timer.cancel();
和postexecute方法
if (pd.isShowing())
pd.dismiss();
if (b) {
dialog.dismiss();
simplealert(result.replace("\"", ""));
} else {
}