How to know programmatically whether MobileData is

2019-08-25 03:17发布

问题:

Is there a way to check programmatically whether MobileData is enabled on Android P?

Before P, we can use getMobileDataEnabled() with reflection like this answer. https://stackoverflow.com/a/12864897/3752013

But after P, reflection methods throw exception... https://developer.android.com/about/versions/pie/restrictions-non-sdk-interfaces#results-of-keeping-non-sdk

Any ideas?

回答1:

Use the following class

public class NetworkEventReceiver extends ConnectivityManager.NetworkCallback {
private final NetworkRequest networkRequest;
private final ConnectivityManager connectivityManager;
private final Context context;


public NetworkEventReceiver(Context context) {
    this.context = context;
    connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    networkRequest = new NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .build();
}

public void enable() {
    connectivityManager.registerNetworkCallback(networkRequest, this);
}

@Override
public void onAvailable(Network network) {
    executeActions(network);
    super.onAvailable(network);
}

@Override
public void onLost(Network network) {
    executeActions(network);
    super.onLost(network);
}

private void executeActions(Network network) {
    try {
        NetworkCapabilities info = connectivityManager.getNetworkCapabilities(network);

        if (info == null || info.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {

            updateStuff();

        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

To enable this service

NetworkEventReceiver monitor = new NetworkEventReceiver(this);
monitor.enable();


回答2:

Use NetworkCapabilities hasCapability()

So something like this:

public boolean hasMobileData() {
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkCapabilities nc = cm.getNetworkCapabilities(cm.getActiveNetwork());
    return nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
}


回答3:

   ConnectivityManager cm =
            (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null &&
                          activeNetwork.isConnectedOrConnecting();

Above code will work for you.

Determine the type of your internet connection

For Wifi

boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;

For Mobile

You can refer @Chris Stillwell answer.