【问题标题】:force close my application when wifi "on" but internet not exist当wifi“打开”但互联网不存在时强制关闭我的应用程序
【发布时间】:2016-01-18 11:01:38
【问题描述】:

我写了这段代码来检查互联网,它可以工作,但我有一个问题,当 wifi 开启但互联网不存在时!!在这种情况下,我的程序强制关闭。

       private class NetCheck extends AsyncTask<String,String,Boolean>
       {

           @Override
           protected Boolean doInBackground(String... args){

               ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
               NetworkInfo netInfo = cm.getActiveNetworkInfo();
               if (netInfo != null && netInfo.isConnected()) {
                   try {
                       URL url = new URL("http://www.google.com");
                       HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                       urlc.setConnectTimeout(1000);
                       urlc.connect();
                       if (urlc.getResponseCode() == 200) {
                           return true;
                       }
                   } catch (MalformedURLException e1) {
                       // TODO Auto-generated catch block
                       e1.printStackTrace();
                   } catch (IOException e) {
                       // TODO Auto-generated catch block
                       e.printStackTrace();
                   }
               }
               return false;

           }

当互联网连接或断开其工作,但当 wifi 开启且互联网不存在时,应用程序强制关闭!

@Override
           protected void onPostExecute(Boolean th){

               if(th == true){


                   getcountHA();


               }
               else{

                   ShowAlertDialog();
               }
           }
       }

什么问题!!

它是我的日志猫

【问题讨论】:

  • ShowAlertDialog()的发布代码;
  • 你可能想 ping 一个实际的 URL 来检查连接,连接的 WiFi 并不总是意味着你连接到互联网。
  • 请异常堆栈跟踪

标签: android android-wifi


【解决方案1】:

用这个方法检查:

public boolean isInternetAvailable() {
        try {
            InetAddress ipAddr = InetAddress.getByName("google.com"); //You can replace it with your name

            if (ipAddr.equals("")) {
                return false;
            } else {
                return true;
            }

        } catch (Exception e) {
            return false;
        }

    }

Credits

【讨论】:

    【解决方案2】:

    我的检查 INTERNET 代码是真实的并且工作得很好,并且强制关闭是因为另一个地方。当 INTERNET 不可用时,服务器会给我一些字符串代码,例如(

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-01
      • 2016-10-12
      相关资源
      最近更新 更多