I am developing an application which requires downloading data from the server.
I use the following code, which works except that it got stuck sometimes at the midst of a file download.
try{ URL url = new URL( dlUrl ); con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(1000); // timeout 1 sec con.setReadTimeout(1000); // timeout 1 sec // get file length int lenghtOfFile = con.getContentLength(); is = url.openStream(); String dir = Environment.getExternalStorageDirectory() + "myvideos"; File file = new File( dir ); if( !file.exists() ){ if( file.mkdir()){ // directory succesfully created } } fos = new FileOutputStream(file + "/" + "video.mp4"); byte data[] = new byte[1024]; long total = 0; while( (count = is.read(data)) != -1 ){ total += count; publishProgress((int)((total*100)/lenghtOfFile)); fos.write(data, 0, count); } } catch (Exception e) { Log.e(TAG, "DOWNLOAD ERROR = " + e.toString() ); } finally{ // close streams } The problem could be that the WIFI connection I am using is unstable, or something missing with my code.
Now I want to add a work around when the download stops, but unfortunately setReadTimeout seems to have no effect!
I tried the solutions suggested in Stackoverflow but none did the job for me.
Am I missing some kind of settings?
Any ideas why setReadTimeout has no effect?
url.openStreamwithcon.getInputStream.