Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: handle unexpected internet disconnect while downloading data

I have here a function that downloads data from a remote server to file. I am still not confident with my code. My question is, what if while reading the stream and saving the data to a file and suddenly I was disconnected in the internet, will these catch exceptions below can really catch that kind of incident? If not, can you suggest how to handle this kind of incident?

Note: I call this function in a thread so that the UI won't be blocked.

public static boolean getFromRemote(String link, String fileName, Context context){ 
        boolean dataReceived = false;
        ConnectivityManager connec =  (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

            if (connec.getNetworkInfo(0).isConnected() || connec.getNetworkInfo(1).isConnected()){
                try {
                        HttpClient httpClient = new DefaultHttpClient();
                        HttpGet httpGet = new HttpGet(link);
                        HttpParams params = httpClient.getParams();
                        HttpConnectionParams.setConnectionTimeout(params, 30000);
                        HttpConnectionParams.setSoTimeout(params, 30000);
                        HttpResponse response;
                        response = httpClient.execute(httpGet);
                        int statusCode = response.getStatusLine().getStatusCode();
                        if (statusCode == 200){
                            HttpEntity entity = response.getEntity();



                            InputStream in = null;
                            OutputStream output = null;

                            try{
                                in = entity.getContent();

                                String secondLevelCacheDir = context.getCacheDir() + fileName;

                                File imageFile = new File(secondLevelCacheDir);

                                output= new FileOutputStream(imageFile);
                                IOUtilities.copy(in, output);
                                output.flush();
                            } catch (IOException e) {
                                Log.e("SAVING", "Could not load xml", e);
                            } finally {
                                IOUtilities.closeStream(in);
                                IOUtilities.closeStream(output);
                                dataReceived = true;

                            }
                        }
                    }catch (SocketTimeoutException e){  
                        //Handle not connecting to client !!!!
                        Log.d("SocketTimeoutException Thrown", e.toString());
                        dataReceived = false;

                    } catch (ClientProtocolException e) {
                        //Handle not connecting to client !!!!
                        Log.d("ClientProtocolException Thrown", e.toString());
                        dataReceived = false;

                    }catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        dataReceived = false;
                        Log.d("MalformedURLException Thrown", e.toString());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        dataReceived = false;
                        Log.d("IOException Thrown", e.toString());
                    } 
                }
            return dataReceived;

        }
like image 867
capecrawler Avatar asked Mar 31 '10 02:03

capecrawler


People also ask

Why does my phone say no Internet connection when I have data?

Sometimes, all you need to do when mobile data is on but no internet connection is to turn on and off Airplane mode. Doing so will cut off your phone from the mobile network and can fix the problem alongside it. On most Android devices, you'll find the Airplane mode toggle in the Quick Settings.

Why do I keep losing my internet connection on my Android phone?

Restart your device. If restarting doesn't work, switch between Wi-Fi and mobile data: Open your Settings app and tap Network & internet or Connections. Depending on your device, these options may be different. Turn Wi-Fi off and mobile data on, and check if there's a difference.

How do I fix my mobile data not working?

Re-Insert Your SIM Card Once removed, wait for 30 seconds and then re-insert your SIM card. Turn your smartphone back on, wait for it to reconnect to networks. Then, check if your mobile data issue has been fixed.

Why does mobile data not work sometimes?

A full shutdown of your iPhone or Android smartphone is worth a try if the restart doesn't work, as it forces a re-connection to your mobile network. Turn off Airplane Mode. Whether you've been in a movie theater or on a plane, don't forget to turn off your mobile device's Airplane Mode afterwards.


1 Answers

I use the following snippet to check if Network is Available before I start a network communication(Prevention better than cure?). Once the communication starts, I can only hope that the network remains available throughout. If not, I would catch Exception thrown and display a message to the user.

public boolean isNetworkAvailable() {
   Context context = getApplicationContext();
   ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
   if (connectivity == null) {
      boitealerte(this.getString(R.string.alert),"getSystemService rend null");
   } else {
      NetworkInfo[] info = connectivity.getAllNetworkInfo();
      if (info != null) {
         for (int i = 0; i < info.length; i++) {
            if (info[i].getState() == NetworkInfo.State.CONNECTED) {
               return true;
            }
         }
      }
   }
   return false;
}

You can attach a DefaultThreadHandler with any thread which would be used if any exception go uncaught in the exception-raising code.

[EDIT: Adding sample code]

//attaching a Handler with a thread using the static function
Thread.setDefaultUncaughtExceptionHandler(handler);

//creating a Handler
private Thread.UncaughtExceptionHandler handler=
        new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread thread, Throwable ex) {
            Log.e(TAG, "Uncaught exception", ex);
            showDialog(ex);
        }
    };

void showDialog(Throwable t) {
        AlertDialog.Builder builder=new AlertDialog.Builder(mContext);
            builder
                .setTitle("Exception")
                .setMessage(t.toString())
                .setPositiveButton("Okay", null)
                .show();
    }
like image 188
Samuh Avatar answered Oct 16 '22 11:10

Samuh