Detect if Android device has Internet connection

后端 未结 15 2668
野性不改
野性不改 2020-11-22 08:54

I need to tell if my device has Internet connection or not. I found many answers like:

private boolean isNetworkAvailable() {
    ConnectivityManager connect         


        
15条回答
  •  孤城傲影
    2020-11-22 09:42

    Check wifi type in connectivity manager:

       //check network connection
        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean hasNetworkConnection = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        System.out.println("Connection ? : " + hasNetworkConnection);
        //check wifi
        boolean hasWifiConnection = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
        System.out.println("Wifi ? : " + hasWifiConnection);
    

    Android Documentation describes 'TYPE_WIFI' as 'A WIFI data connection. Devices may support more than one.'

提交回复
热议问题