Search code examples
javaandroidvpnstrongswan

Always-on VPN switch on programmatically android


Can Always-on VPN switch be on programmatically?

I have added the device admin permission. After that i have set always on in with device admin

mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    mDeviceAdminSample = new ComponentName(this, DeviceAdminReceiver.class);
    isAdminApp = mDPM.isAdminActive(mDeviceAdminSample);

    if (isAdminApp) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                mDPM.setAlwaysOnVpnPackage(mDeviceAdminSample,"", true);
            }
        } catch (PackageManager.NameNotFoundException namenotfoundexception) {
            namenotfoundexception.printStackTrace();
        } catch (Exception ex) {
        }
    }

but it's not enabling the always on.

i have added package name insted of

mDPM.setAlwaysOnVpnPackage(mDeviceAdminSample,"my.app.package.name", true);

but still not enabling the switch.

Then what this code is doing? How can i enable it programatically?

I want this to be like below image

Always-on VPN


Solution

  • According to docs, setAlwaysOnVpnPackage can only be used by the profile owner (usually the MDM client on work profile) or device owner (for fully managed devices):

    Called by a device or profile owner to configure an always-on VPN connection through a specific application for the current user. This connection is automatically granted and persisted after a reboot.

    As a personal profile user - I don't want my VPN to decide for itself when to connect (set always on programmatically will immediately connect the VPN, if implemented correctly).

    As a work profile user (wearing the hat of an employee), it's not my decision, but my organization's (via the profile owner app).

    So, all in all, this behavior makes sense.

    Update:

    Instead implementing MDM, which could take a lot of work, you can clone, build and debug Google's Test DPC app, which have everything you need to test toggling always-on VPN programmatically.

    It also have million other things, which you don't need so be sure to ignore the rest :)

    I haven't looked at their code, but I suggest searching for usages of setAlwaysOnVpnPackage function.

    Google's Test DPC app:

    • Link to Play Store
    • Link to GitHub repo (to build & debug it yourself)