Wednesday, June 5, 2013

[android help] asynctask download file network connection drop


asynctask download file network connection drop



I have an application that downloads multiple files (and checks the download speed) within an Asynctask. However, when I am connected to 3G (and there is a handover) or the device switches form WiFi to 3G, my application freezes and I can not handle this problem



@Override
protected Integer doInBackground(String... sUrl) {

try {
speed=0; //initial value
int i=0;
while ((i


URL url = new URL(sUrl[i]);
URLConnection connection = url.openConnection();
connection.setReadTimeout(10000);
connection.connect();

int fileLength = connection.getContentLength();

// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(file);

byte data[] = new byte[1024*1024]; //1MB buffer
long total = 0;
int count;
long start = System.currentTimeMillis();
while ((count = input.read(data)) != -1) {
total += count;

publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
long finish = System.currentTimeMillis();
long tempSpeed= (fileLength *8)/(finish-start);
if (tempSpeed>speed) {
speed=tempSpeed;
}


output.flush();
output.close();
input.close(); // connection is closed
i++;
}
}catch(SocketTimeoutException e) {
exceptions.add(e);
messageProgressDialog.setCancelable(true);
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(gui.getActivity()).create();
alertDialog.setTitle("Network problem");
alertDialog.setMessage("connection dropped");
alertDialog.show();
} catch (IOException e) {
exceptions.add(e);
messageProgressDialog.setCancelable(true);
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(gui.getActivity()).create();
alertDialog.setTitle("IOException");
alertDialog.setMessage("IOException error");
alertDialog.show();
} catch(Exception e) {
exceptions.add(e);
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(gui.getActivity()).create();
alertDialog.setTitle("Exception");
alertDialog.setMessage("Exception error");
alertDialog.show();
}


return 1;
}


I have read many topics on stackoverflow, however none of them could help me solve the prolem I have with my application. I have the try/catch clause, but it doesn't seem to make a difference. When I am using 3G and the phone connects to annother antenna, or there is a network problem the application freezes. What can I do ?



.

stackoverflow.comm

No comments:

Post a Comment

Google Voice on T-Mobile? [General]

Google Voice on T-Mobile? So I recently switched from a GNex on Verizon to a Moto X DE on T-Mobile. I had always used Google Voice for my v...