how to get network connection type without using READ_PHONE_STATE permission in android 10?

Viewed 168

One of the things android 10 is changing is that we cannot get READ_PHONE_STATE automatically, And have to direct the user to manually give the permission by going to app info > permissions > phone > turn on.

is there any way to get network state (if the phone is on wifi / 3g, etc) on android 10 and above Without directing the user to go to the application settings by himself and change the permission manually?

I was thinking to bypass the permission asking with

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkCapabilities caps = cm.getNetworkCapabilities(cm.getActivityNetwork());
boolean isMobile = caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR);
boolean isWifi = caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);

would that be ok and then not needed to use the READ_PHONE_STATE permission ?

1 Answers

There is a class NetworkInfo it have a function getTypeName() that return string value contain MOBILE or WIFI

I try to write function I hope it will be helpful for you :

    /**
     * @param mType : type of network connection "MOBILE" or "WIFI"
     * @return : true of false
     */
    public boolean isMyType(String mType) {
        ConnectivityManager connectivityManager = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        //
        if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
            return activeNetworkInfo.getTypeName().equals(mType);
        } else {
            // no internet connection
            return false;
        }
    }

than you can call it :


  boolean isMobile = isMyType("MOBILE");
  boolean isWifi = isMyType("WIFI");

  // for logcat debug
  Log.i("typeNetwork", "is mobile :" + isMobile);
  Log.i("typeNetwork", "is wifi :" + isWifi);

let me know if this works for you..

Related