Android: Check internet connection - returns true (incorrectly)

别来无恙 提交于 2019-12-24 13:03:32

问题


To check for internet connectivity, i am using this code:

public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        //return netInfo != null && netInfo.isConnectedOrConnecting();
        return netInfo != null && netInfo.isAvailable() && netInfo.isConnected();
    }

This is the most commonly used code i found everywhere - however it is not working reliably.

This is returning true, although i am unable to use internet.
Other apps on my mobile correctly give message: 'Can't connect to internet'.

EDIT 1
It appears that it returns true when internet connection is there - even though it is unusable for some reason.
If i switch off the Mobile Data/Internet on my phone - then this method correctly returns false.


回答1:


Those all will tell you if your device is connected or not, they do not tell you the internet status...
For that you should use this code...

 private boolean isOnline() {
            try{
                // ping to googlevto check internet connectivity
                Socket socket = new Socket();
                SocketAddress socketAddress = new InetSocketAddress("8.8.8.8", 80);
                socket.connect(socketAddress, 3000);
                socket.close();
                return true;
            } catch (Exception e) {
                 // internet not working
                 return false
            }
 }

You must do this in async task or it will give you network on main thread exception...
I am assuming you are already calling isOnline method in async task.

Well if you are not using this in an async task,
You must use it here like this....

for example you want to go to xyz activity only if internet available

private class GoToXYZActivity extends AsyncTask<String, Void, Void> {
     boolean internetAvailable;
     protected String doInBackground(String... urls) {
         //THIS METHOD WILL BE CALLED AFTER ONPREEXECUTE
         //YOUR NETWORK OPERATION HERE
         internetAvailable = inOnline();
         return null;
     }

     protected void onPreExecute() {
         super.onPreExecute();
         //THIS METHOD WILL BE CALLED FIRST
         //DO OPERATION LIKE SHOWING PROGRESS DIALOG PRIOR TO BEGIN NETWORK OPERATION
     }

     protected void onPostExecute(String result) {
         super.onPostExecute();
         //TNIS METHOD WILL BE CALLED AT LAST AFTER DOINBACKGROUND
         //DO OPERATION LIKE UPDATING UI HERE
         if (internetAvailable)
             /// goto xyz activity
         else
             /// toast - no internet
     }
 }

And on click event you must call this method

 new GoToXYZActivity().execute();



回答2:


  public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null) 
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null) 
                  for (int i = 0; i < info.length; i++) 
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }

          }
          return false;
    }


来源:https://stackoverflow.com/questions/28448197/android-check-internet-connection-returns-true-incorrectly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!