2015-07-22 76 views
0

在我的应用程序中,我使用广播接收器来捕获Internet连接和断开连接状态。它的工作正常。这里是代码:如何在广播接收器中取消http请求?

public class CheckConnectivity extends BroadcastReceiver{ 

    @Override 
    public void onReceive(Context context, Intent arg1) { 

     boolean isNotConnected = arg1.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); 
     if(isNotConnected){ 
      Toast.makeText(context, "Disconnected", Toast.LENGTH_LONG).show(); 

     } 
     else 
     { 
      Toast.makeText(context, "Connected", Toast.LENGTH_LONG).show(); 
     } 

    } 
} 

我在我的应用程序中使用http网络服务。我在不同的课上写了他们。 HttpConnect.java:

public class HttpConnect { 
    public static String finalResponse; 
    public static HttpURLConnection con = null; 
    public static String sendGet(String url) { 

     try { 
      StringBuffer response = null; 
      //String urlEncode = URLEncoder.encode(url, "UTF-8"); 
      URL obj = new URL(url); 
      Log.e("url", obj.toString()); 

      con = (HttpURLConnection) obj.openConnection(); 

      // optional default is GET 
      con.setRequestMethod("GET"); 

      //add request header 
      con.setConnectTimeout(10000); 
      int responseCode = con.getResponseCode(); 

      BufferedReader in = new BufferedReader(
        new InputStreamReader(con.getInputStream())); 
      String inputLine; 
      response = new StringBuffer(); 

      while ((inputLine = in.readLine()) != null) { 
       response.append(inputLine); 
      } 
      in.close(); 
      finalResponse = response.toString(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     //print result 
     return finalResponse; 

    } 
} 

我的问题是,如何断开或取消HTTP请求时,广播接收器说没有连接。 我试过以下代码:

if(isNotConnected){ 
      Toast.makeText(context, "Disconnected", Toast.LENGTH_LONG).show(); 
      if(HttpConnect.con != null) 
      { 
       HttpConnect.con.disconnect(); 
      } 
     } 

但它不工作。任何人都可以告诉我,当广播接收器捕获丢失的连接时如何取消http请求?

回答

1

您应该创建一个方法类似如下:

public static boolean isOnline(Context mContext) { 
     ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
     if (netInfo != null && netInfo.isConnectedOrConnecting()) { 
      return true; 
     } 
     return false; 
    } 

而且你的HTTP调用之前,你应该检查,如果返回true,这意味着互联网可如果是false,这意味着互联网不可用,您可以停止您的http呼叫。

另外,如果您的电话已经启动,你应该设置请求超时值有好像是30秒,如果没有互联网,你会得到TimeoutError

+0

然后例外超时错误 –

+0

都能跟得上应用程序崩溃,您应处理异常并向用户显示适当的消息或重试,或者按照应用程序流程处理任何情况。 –