Check internet connection in android (not network connection)

前端 未结 7 874
孤城傲影
孤城傲影 2020-12-20 03:44

I have a problem with checking internet connection in android at runtime. I use some different methods to check internet connection but i don\'t know which one is better . b

相关标签:
7条回答
  • 2020-12-20 04:23

    You can do it like this

    uses-permission android:name="android.permission.INTERNET"

    uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"

     private boolean checkInternet(Context context) {
        // get Connectivity Manager object to check connection
        ConnectivityManager connec
                =(ConnectivityManager)context.getSystemService(context.CONNECTIVITY_SERVICE);
    
        // Check for network connections
        if ( connec.getNetworkInfo(0).getState() ==
                android.net.NetworkInfo.State.CONNECTED ||
                connec.getNetworkInfo(0).getState() ==
                        android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() ==
                        android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
            Toast.makeText(context, " Connected ", Toast.LENGTH_LONG).show();
            return true;
        }else if (
                connec.getNetworkInfo(0).getState() ==
                        android.net.NetworkInfo.State.DISCONNECTED ||
                        connec.getNetworkInfo(1).getState() ==
                                android.net.NetworkInfo.State.DISCONNECTED  ) {
            Toast.makeText(context, " Not Connected ", Toast.LENGTH_LONG).show();
            return false;
        }
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题