In our app we have many different modules that can make network requests on their own. App has option to use VPN for secure connection. VPN service is only handling network for our app. My problem is: on app cold start, when VPN feature is enabled, how to prevent modules from making network requests until VPN service is started.
Asked
Active
Viewed 62 times
1 Answers
1
I had similar problem in my project, but I had a single module that need to wait for establishing VPN. Anyway, I have a small code to detect if a VPN is connected or not.
Here is the code:
class VpnMonitor {
private final String VPN_INTERFACE = "tun0";
private OnVpnStatusChange mCallback;
private MonitorThread mThread = null;
private Handler mHandler = new Handler(Looper.getMainLooper());
public interface OnVpnStatusChange {
void onVpnConnect();
void onVpnDisconnect();
}
VpnMonitor() {
this(null);
}
VpnMonitor(@Nullable OnVpnStatusChange callback) {
mCallback = callback;
}
void startMonitor() {
if ((mThread == null) || !mThread.isAlive()) {
mThread = new MonitorThread();
mThread.start();
}
}
void stopMonitor() {
if (mThread != null) {
mThread.terminate();
try {
mThread.join();
} catch (Exception e) {
}
mThread = null;
}
}
boolean isVpnConnectionUp() {
try {
ArrayList<NetworkInterface> infs = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface inf : infs) {
if (inf.getName().equals(VPN_INTERFACE) && inf.isUp() && inf.getInterfaceAddresses().size() > 0) {
return true;
}
}
} catch (SocketException e) {
return false;
}
return false;
}
private class MonitorThread extends Thread {
private volatile boolean mRunning = true;
void terminate() {
mRunning = false;
}
@Override
public void run() {
mRunning = true;
for (int i = 0; i < 5; i++) {
try {
delay(100);
ArrayList<NetworkInterface> infs = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface inf : infs) {
if (inf.getName().equals(VPN_INTERFACE)) {
for (int r = 0; r < 10; r++) {
if (!mRunning) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (mCallback != null) {
mCallback.onVpnDisconnect();
}
}
});
return;
}
if (inf.isUp() && inf.getInterfaceAddresses().size() > 0) {
delay(1000);
mHandler.post(new Runnable() {
@Override
public void run() {
if (mCallback != null) {
mCallback.onVpnConnect();
}
}
});
return;
}
delay(50);
}
}
}
} catch (SocketException e) {
}
}
mHandler.post(new Runnable() {
@Override
public void run() {
if (mCallback != null) {
mCallback.onVpnDisconnect();
}
}
});
}
private void delay(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
Maybe it can help you too. Feel free to change it as you please.

Afshin
- 8,839
- 1
- 18
- 53