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
Android Getting Exact Scroll Position in Listview
Sending Message to a Handler on a Dead Thread When Getting a Location from an Intentservice
Using Google Places API in Android
Android - How to Set Background Color of All Screens
How to Change Option Menu Icon in The Action Bar
Android Studio Where Is Gradle.Properties File
Fragment in Viewpager Not Restored After Popbackstack
How to Set Status Bar Background as Gradient Color or a Drawable in Android
Linearlayout Height in Oncreate Is 0
How to Hide The System/Navigation Bar in Android Ics
How to Get Total Ram Size of a Device
How to Disable "Next" Button on a Edittext Software Keyboard (Replace with "Done" Button)
How to Setup Multiple Alarms in Android
Inconsistency Detected in Recyclerview, How to Change Contents of Recyclerview While Scrolling
Camera Preview Stretched on Few Android Devices
Android Device Monitor "Data" Folder Is Empty