Search code examples
androidmonitoringvpn

Check if a VPN connection is active in Android?


I have a third party VPN app on my non-rooted Android 4.4 device, and want to write a background service to monitor the VPN connection and alert the user if the VPN connection has been broken.

Is there a way to do this? I couldn't find any way using the VPNService API.

Thanks -D


Solution

  • Here is kotlin coroutines flow solution

    val isVpnActiveFlow = callbackFlow {
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
        if (connectivityManager == null) {
            channel.close(IllegalStateException("connectivity manager is null"))
            return@callbackFlow
        } else {
            val callback = object : ConnectivityManager.NetworkCallback() {
                override fun onAvailable(network: Network) {
                    channel.trySend(true)
                }
                override fun onLost(network: Network) {
                   channel.trySend(false)
                }
            }
            connectivityManager.registerNetworkCallback(
    
                //I have to investigate on this builder!
                NetworkRequest.Builder()
                        .addTransportType(NetworkCapabilities.TRANSPORT_VPN)
                        .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
                        .build(),
                callback
            )
            awaitClose {
                connectivityManager.unregisterNetworkCallback(callback)
            }
        }
    }