How to check if a device is connected to the Internet

Asked 2 years ago, Updated 2 years ago, 97 views

I want to make sure the device is connected to the Internet.

There is a method called isAvailable() in the NetworkInfo class, and I think you can use this.

NetworkInfo ni = new NetworkInfo();
if (!ni.isAvailable()) {
    // // do something
}

The constructor NetworkInfo is not visible.

I got this error. Is there any other way to get NetworkInfo?

android internet-connection android-internet

2022-09-21 14:53

1 Answers

connectivitymanager of getactivenetworkinfo (), , if the Internet is connected networkinfo the return or null back.

You can check if the Internet is connected with this return value.

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Please refer to the sauce

Oh! And

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

You must go to the Android manifest file and insert the above code.


2022-09-21 14:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.