开发者

Android: handle unexpected internet disconnect while downloading data

开发者 https://www.devze.com 2022-12-25 08:36 出处:网络
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 sudde

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.toStri开发者_Python百科ng());
                        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;

        }


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();
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消