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請求?
然後例外超時錯誤 –
都能跟得上應用程序崩潰,您應處理異常並向用戶顯示適當的消息或重試,或者按照應用程序流程處理任何情況。 –