ChatGPT解决这个技术问题 Extra ChatGPT

Detect whether there is an Internet connection available on Android [duplicate]

This question already has answers here: Closed 10 years ago.

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?

[This][1] might help as well [1]: stackoverflow.com/questions/6179906/…
None of the answers here actually answer the question of checking if there is a connection to the internet, only if you are connected to a network at all. See this answer for an example of just trying to make an outgoing TCP connection to test this: stackoverflow.com/a/35647792/1820510
For anyone looking at this in 2020: teamtreehouse.com/community/…

m
m.sajjad.s

The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none of the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available or not.

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

You will also need:

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

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.


It it worth to take a look at connectiontimeout if somebody (unnecessarily) try call this function before making http call! :-)
To be safe I would return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
If you are creating a Utils method i.e. not accessing this from where Context reference is available, you'll need to pass Context as an argument.
This does not check if the phone is connected to the internet. Only that a network connection has been made.
@Mr.Hyde Unfortunately, no. This way is checking only if a network connection has been made, but does not check that device is connected to the internet. To really know about active internet connection, you should to use HttpURLConnection to some host, ping some host (e.g. google.com) or try to use InetAddress.getByName(hostName).isReachable(timeOut)
S
Squonk

I check for both Wi-fi and Mobile internet as follows...

private boolean haveNetworkConnection() {
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) {
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            if (ni.isConnected())
                haveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                haveConnectedMobile = true;
    }
    return haveConnectedWifi || haveConnectedMobile;
}

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.


The code is good, I just wish people would stick to Java coding style when writing java haveConnectedWifi, haveConnectedMobile. I know it's a small thing, but consistent code is more readable.
While on good practice it's better to have the String on the left and not use equalsIgnoreCase if you don't have to: if ("WIFI".equals(ni.getTypeName()))
@Stuart Axon: Oh well, that's just how it goes I suppose. I've programmed more languages than I can remember since I started back in the late 1970's and I've obviously picked up many bad habits. In general I go on the principle that if it works then...well, it works and that's all I care about. The code snippet above is completely self-contained and it's easy for anybody with reasonable programming experience to work out and (most importantly) if someone were to cut and paste it into their own code it would work for them. Sorry for being an Android/Java noob.
Wasn't after points or anything (or however SO works) - I found the code useful, but I guess in my grumpy way was trying to give some semi helpful feedback.
@BoD: getType() provides a finer level of granularity (I believe) and might return TYPE_MOBILE, TYPE_MOBILE_DUN, TYPE_MOBILE_HIPRI and so on. I'm not interested in the specifics of what type of 'mobile' connection is available and getTypeName() will simply return 'MOBILE' for all of them.
s
sagar

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:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;


public class AppStatus {

    private static AppStatus instance = new AppStatus();
    static Context context;
    ConnectivityManager connectivityManager;
    NetworkInfo wifiInfo, mobileInfo;
    boolean connected = false;

    public static AppStatus getInstance(Context ctx) {
        context = ctx.getApplicationContext();
        return instance;
    }

    public boolean isOnline() {
        try {
            connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        connected = networkInfo != null && networkInfo.isAvailable() &&
                networkInfo.isConnected();
        return connected;


        } catch (Exception e) {
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
            Log.v("connectivity", e.toString());
        }
        return connected;
    }
}

Step 2: Now to check if the your device has network connectivity then just add this code snippet where ever you want to check ...

if (AppStatus.getInstance(this).isOnline()) {

    Toast.makeText(this,"You are online!!!!",8000).show();

} else {

    Toast.makeText(this,"You are not online!!!!",8000).show();
    Log.v("Home", "############################You are not online!!!!");    
}

do you really need to check isAvailable ? I would think isConnected is enough.
also if you pass the Context to the constructor why do you need to do that in isOnline?
this crashes my phone. does this still works in June 2014 ?
@AlexanderMalakhov actually isAvailable should be the first check. I have found that if a connection interface is available, this is true. Sometimes (for example, when 'Restrict background data' setting is enabled) isConnected can be false to mean that the interface has no active connection but isAvailable is true to mean the interface is available and you can establish a connection (for example, to transmit foreground data).
I did a simple test. I pulled out the input ethernet cable from my router and then called this method. So the device was connected to WI-Fi but the Wifi itself was not connected to internet. Guess what! Even then it returned true. So if I want to make sure that device is connected to internet I would ping a well known website rather than checking this.
O
Octavian A. Damiean

Also another important note. You have to set android.permission.ACCESS_NETWORK_STATE in your AndroidManifest.xml for this to work.

_ how could I have found myself the information I needed in the online documentation?

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.


The description of the ConnectivityManager class tells me nothing about how to use the class, it's just a listing of method signatures and constant values. There's more info in the answers to this question than there is in that documentation. No mention of the fact that getActiveNetworkInfo() can return null, no mention of the need to have ACCESS_NETWORK_STATE permission, etc. Where exactly did you find this info, other than the Android source?
Good point dfjacobs. Stackoverflow seems to be the goto source these days for lack of decent cookbook examples.
Requires the ACCESS_NETWORK_STATE permission. is stated here.
H
Hanry

The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none if the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available.

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

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. Networks 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.

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.


Why would you ever want it to return an object if there isn't a single active connection?
Z
Ziem

Probably I have found myself:

ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();

Expect that getActiveNetworkInfo() can return null if there is no active network e.g. Airplane Mode
Yes it will return null and this is undocumented.
yes, so do a null check first activeNetwork != null && activeNetwork.isConnectedOrConnecting();
I like this line: boolean isWifiConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting() && activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
Can anyone explain this line in more detail looks strange to me: first activeNetwork != null