2010-03-31 44 views
8

我在这里有一个将数据从远程服务器下载到文件的功能。我对我的代码仍然没有信心。我的问题是,如果在读取流并将数据保存到文件中并突然在互联网上断开连接时,如果在下面捕获异常会真的发现这种事件?如果不是,你能建议如何处理这类事件吗?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; 
} 

如果在异常提升代码中未捕获到任何异常,则可以将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 2010-04-09 11:58:57

+0

我没有在代码中使用它们(仅在理论上知道它们),但我认为使用它们非常简单。我在上面编辑了我的答案;看一看。 – Samuh 2010-04-09 12:57:03

相关问题