我正在制作带有下载程序的应用程序,它会下载某个文件。如果我在下载文件时关闭Wi-Fi,则应用程序崩溃。
这是日志:recvfrom失败:ETIMEDOUT(连接超时)
我有条件,但似乎没有用。如果我调试代码,它似乎进入条件。
<meta http-equiv="Content-Security-Policy" content=" default-src * gap://ready file:; script-src 'self' 'unsafe-inline' 'unsafe-eval' cdn.firebase.com https://.firebaseio.com https://*.firebaseio.com; object-src 'self'; style-src 'self' 'unsafe-inline' ; connect-src * 'self' *.firebaseapp.com https://.firebaseio.com wss://*.firebaseio.com * ">
我希望在关闭Wi-Fi时暂停下载过程。有没有办法做到这一点? 提前谢谢。
所有代码
else {
Thread.sleep(4000); //doesn't work, doesn't sleep
downloadresult = false;
}
如果我调试代码,它可以很好地工作。如果应用程序无法下载文件,我希望应用程序等待4000毫秒,然后再试一次,但如果我运行应用程序,它会崩溃。
如何暂停/恢复下载过程。谢谢
答案 0 :(得分:1)
我解决了问题:)
感谢所有回复,我喜欢它&lt; 3
代码:
protected String doInBackground(String... f_url) {
try {
long total = 0;
URL url = new URL(f_url[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
/* if (file.exists())
{
connection.setAllowUserInteraction(true);
connection.setRequestProperty("Range", "bytes=" + lenghtOfFile + "-");
}*/
if(file.exists()){
deneme = file.length();
connection.setRequestProperty("Range", "bytes="+(file.length())+"-");
}
else{
connection.setRequestProperty("Range", "bytes=" + deneme + "-");
}
String connectionField = connection.getHeaderField("content-range");
if (connectionField != null)
{
String[] connectionRanges = connectionField.substring("bytes=".length()).split("-");
deneme = Long.valueOf(connectionRanges[0]);
}
if (connectionField == null && file.exists())
file.delete();
connection.setConnectTimeout(14000);
connection.setReadTimeout(20000);
connection.connect();
long lenghtOfFile = connection.getContentLength() + deneme;
RandomAccessFile output = new RandomAccessFile(file,"rw");
BufferedInputStream input = new BufferedInputStream(connection.getInputStream());
output.seek(deneme);
byte data[] = new byte[1024];
int lastcount = 0;
while ((count = input.read(data,0,1024)) != -1) {
if (isCanceled) { // this code waiting the click button :)
file.delete();
downloadresult = false;
break;
}
if (intCheck()) { // check internet and download
total += count;
downloadresult = true;
int ProgBarCount = (int) ((total * 100) / lenghtOfFile);
if (ProgBarCount > lastcount) {
lastcount = ProgBarCount;
publishProgress(Integer.toString(ProgBarCount));
}
output.write(data, 0, count);
}
}
// output.flush();
output.close();
input.close();
}
catch (Exception e) {
e.printStackTrace();
exmessage = e.getMessage().toString();
downloadresult = false;
}
return null;
}
答案 1 :(得分:0)
不要暂停后台任务。出现任何问题时取消任务。请记住,您的应用足够智能,可以启动后台任务。它将足够聪明,以后再次重新启动它。如果您要暂停后台任务,则应仅在用户遗赠处暂停。