我正在尝试通过这段代码下载一些 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]);
最佳答案
在点击下载按钮时
在类 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();
和后执行方法
if (pd.isShowing())
pd.dismiss();
if (b) {
dialog.dismiss();
simplealert(result.replace("\"", ""));
} else {
}
关于android - 从服务器下载 Xml。超时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21231892/