How to check Wifi is connected, but no Internet access in Android

冷暖自知 提交于 2019-11-30 04:59:17

You could try something like this:

public void checkOnlineState() {
    ConnectivityManager CManager =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo NInfo = CManager.getActiveNetworkInfo();
    if (NInfo != null && NInfo.isConnectedOrConnecting()) {
        if (InetAddress.getByName("www.xy.com").isReachable(timeout))
        {  
         // host reachable  
        }
         else
         {    
         // host not reachable  
         }  
    }
    return;
}

dont forget the access

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Hope it will work :)

Sunil Kumar

Use this :

public static boolean isInternetOn(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        // test for connection
        if (cm.getActiveNetworkInfo() != null
                && cm.getActiveNetworkInfo().isAvailable()
                && cm.getActiveNetworkInfo().isConnected()) {
            Log.v(TAG, "Internet is working");
            // txt_status.setText("Internet is working");
            return true;
        } else {
            // txt_status.setText("Internet Connection Not Present");
            Log.v(TAG, "Internet Connection Not Present");
            return false;
        }
    }

Hope this helps.

In addition to what you are doing right now,you can use BroadcastReceiver for your application to get notified whenever the connectivity changes by registering <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/> intent.

Have a look at docs: BroadcastReceiver and Connectivity Monitoring for detailed description.

I hope it will be helpful !

minjie
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            return true;
        }
        return false;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!