Android:当互联网无法访问但连接到网络时广播或回叫

时间:2014-09-15 10:27:05

标签: android broadcastreceiver android-internet

我必须处理以下特殊情况:

  • 我的手机,因此应用程序已连接到Wifi路由器。
  • 现在,路由器的以太网电缆被取出,因此互联网连接丢失。
  • 但手机仍然连接到这台Wifi路由器。

在上述情况发生时,我可以获得广播或回调吗?

1 个答案:

答案 0 :(得分:0)

最简单易行的方法是:ping到这里的任何服务器。我ping谷歌,检查响应是否为空;或者......当你怀疑连接时,这个函数在android活动中调用。

public void GET(){

    String result = "";
    HttpResponse response;
    HttpEntity entity;

    try {

        HttpPost httppost = new HttpPost("http://google.com");
        DefaultHttpClient httpclient = getHttpClientImpl();

        response = httpclient.execute(httppost);
        entity = response.getEntity();

        if (entity != null) {
            InputStream is = entity.getContent();
            if (is != null) {
                StringBuilder sb = new StringBuilder();
                String line;
                try {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(is, "UTF-8"), 8 * 1024);
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);// .append("\n");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    is.close();
                }
                result = sb.toString();
                if (responseXML.equals("")){

                //  Internet connectivity is lost.

                }else {

                //  Internet connectivity still here xnjoy.

                }

            }
            entity.consumeContent();
        }
        httpclient.getConnectionManager().shutdown();

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

 }