Home > Software design >  Detect VPN running in Android Phone
Detect VPN running in Android Phone

Time:02-19

I am trying to detect if VPN is running on the phone. I have implemented the below code but it reports crashes on Firebase Crashlytics.

ConnectivityManager connectivityManager = (ConnectivityManager) activity.getSystemService(activity.CONNECTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            @SuppressLint("MissingPermission")
            Network activeNetwork = connectivityManager.getActiveNetwork();
            @SuppressLint("MissingPermission")
            NetworkCapabilities caps = connectivityManager.getNetworkCapabilities(activeNetwork);
            boolean vpnInUse = caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN);

The Crash reported is

Fatal Exception: java.lang.RuntimeException
Unable to resume activity {com.my.app/com.my.app.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.net.NetworkCapabilities.hasTransport(int)' on a null object reference

Kindly help to resolve this issue.

CodePudding user response:

caps is null, what else we can insight... just make some preventing if(caps!=null)... below some shorten way for checking null state

NetworkCapabilities caps = connectivityManager.getNetworkCapabilities(activeNetwork);
boolean vpnInUse = caps!=null && caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN);

CodePudding user response:

Looks like you are getting null reference of NetworkCapabilities. Please look into the developer.android docs.

This document says

This will return null if the network is unknown or if the |network| argument is null. This will remove any location sensitive data in TransportInfo embedded in NetworkCapabilities#getTransportInfo(). Some transport info instances like WifiInfo contain location sensitive information. Retrieving this location sensitive information (subject to app's location permissions) will be noted by system. To include any location sensitive data in TransportInfo, use a NetworkCallback with NetworkCallback#FLAG_INCLUDE_LOCATION_INFO flag.

  • Related