【发布时间】:2015-07-22 13:52:27
【问题描述】:
在我的应用程序中,我使用广播接收器来捕获互联网连接和断开状态。它工作正常。代码如下:
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 请求?
【问题讨论】:
标签: android web-services http broadcastreceiver