Possible Duplicate:
How to check internet access on Android? InetAddress never timeouts
I need to detect whether the Android device is connected to the Internet.
The NetworkInfo
class provides a non-static method isAvailable()
that sounds perfect.
Problem is that:
NetworkInfo ni = new NetworkInfo();
if (!ni.isAvailable()) {
// do something
}
throws this error:
The constructor NetworkInfo is not visible.
Safe bet is there is another class that returns a NetworkInfo
object. But I don't know which.
- How to get the above snippet of code to work?
- How could I have found myself the information I needed in the online documentation?
- Can you suggest a better way for this type of detection?
The
getActiveNetworkInfo()
method ofConnectivityManager
returns aNetworkInfo
instance representing the first connected network interface it can find ornull
if none of the interfaces are connected. Checking if this method returnsnull
should be enough to tell if an internet connection is available or not.You will also need:
in your android manifest.
Edit:
Note that having an active network interface doesn't guarantee that a particular networked service is available. Network issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service.
You will also need:
getActiveNetworkInfo() shouldn't never give null. I don't know what they were thinking when they came up with that. It should give you an object always.
Also another important note. You have to set
android.permission.ACCESS_NETWORK_STATE
in your AndroidManifest.xml for this to work.You just have to read the documentation the the classes properly enough and you'll find all answers you are looking for. Check out the documentation on ConnectivityManager. The description tells you what to do.
Probably I have found myself:
I check for both Wi-fi and Mobile internet as follows...
Obviously, It could easily be modified to check for individual specific connection types, e.g., if your app needs the potentially higher speeds of Wi-fi to work correctly etc.
Step 1: Create a class AppStatus in your project(you can give any other name also). Then please paste the given below lines into your code:
Step 2: Now to check if the your device has network connectivity then just add this code snippet where ever you want to check ...