2010-03-31 9 views
8

원격 서버에서 파일로 데이터를 다운로드하는 기능이 있습니다. 나는 여전히 내 코드에 자신이 없다. 내 질문은 스트림을 읽고 파일에 데이터를 저장하는 동안 갑자기 인터넷에서 연결이 끊어지면 아래의 예외를 catch하면 실제로 그런 종류의 사건을 잡을 수 있을까요? 그렇지 않은 경우 이러한 종류의 사건을 처리하는 방법을 제안 할 수 있습니까?Android : 데이터를 다운로드하는 중에 예기치 않은 인터넷 연결 끊기 처리

참고 : 스레드에서이 함수를 호출하여 UI가 차단되지 않도록합니다.

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; 

     } 

답변

5

는 내가 네트워크 통신을 시작하기 전에 네트워크를 사용할 수 있는지 확인하기 위해 다음 코드를 사용 (치료보다 예방을?). 통신이 시작되면 네트워크 전체에서 계속 사용할 수 있기를 바랍니다. 그렇지 않으면 예외가 발생하여 사용자에게 메시지를 표시합니다.

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; 
} 

당신은 예외 예외 모금 코드에서 catch되지 않은 가면 사용되는 모든 스레드와 DefaultThreadHandler을 첨부 할 수 있습니다.

[편집 : 추가 샘플 코드]

//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

당신이 DefaultThreadHandler를 생성하는 방법에 대한 몇 가지 예를 들어 줄 수 있습니까? 나는 그것을 만드는 경험이 없습니다. 감사. – capecrawler

+0

나는 코드에서 그것들을 사용하지 않고있다. (이론적으로 만 알고있다.) 사용법은 꽤 간단하다. 위의 내 대답을 편집했습니다. 보세요. – Samuh

관련 문제