Check If a Vpn Connection Is Active in Android

Check if a VPN connection is active in Android?

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)
}
}
}

Detect if an always-on VPN is configured on Android

In the end, it seems this isn't possible on a normal device any way that I can find. I think is possible if you're a device admin, but that requires managed enterprise devices etc.

For now, I've handled this by watching for near-instant (less than 200ms) VPN setup failures (between running startActivityForResult(vpnIntent) and receiving onActivityResult with RESULT_CANCELED) and then showing a helpful message in that case.

Full implementation is in https://github.com/httptoolkit/httptoolkit-android/commit/928fbf92a4f868042789471be0d42800a226194b in case you're trying to do the same.

Check VPN Status Connected or Not Connected

This is works for me: Tested from API 16 to 23:

 List<String> networkList = new ArrayList<>();
try {
for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
if (networkInterface.isUp())
networkList.add(networkInterface.getName());
}
} catch (Exception ex) {
Timber.d("isVpnUsing Network List didn't received");
}

return networkList.contains("tun0");


Related Topics



Leave a reply



Submit