Example usage for android.net VpnService prepare

List of usage examples for android.net VpnService prepare

Introduction

In this page you can find the example usage for android.net VpnService prepare.

Prototype

public static Intent prepare(Context context) 

Source Link

Document

Prepare to establish a VPN connection.

Usage

From source file:hosts.file.localvpn.LocalVPN.java

private void startVPN() {
    Log.i(TAG, "Trying to start.");
    Intent vpnIntent = VpnService.prepare(this);
    if (vpnIntent != null)
        startActivityForResult(vpnIntent, VPN_REQUEST_CODE);
    else// ww  w  .  j  av  a 2s.  co  m
        onActivityResult(VPN_REQUEST_CODE, RESULT_OK, null);
}

From source file:com.avalond.ad_blocak.vpn.AdVpnService.java

public static void checkStartVpnOnBoot(Context context) {
    Log.i("BOOT", "Checking whether to start ad buster on boot");
    Configuration config = FileHelper.loadCurrentSettings(context);
    if (config == null || !config.autoStart) {
        return;/*from w w  w . java2  s. co  m*/
    }

    if (VpnService.prepare(context) != null) {
        Log.i("BOOT", "VPN preparation not confirmed by user, changing enabled to false");
    }

    Log.i("BOOT", "Starting ad buster from boot");

    Intent intent = new Intent(context, AdVpnService.class);
    intent.putExtra("COMMAND", Command.START.ordinal());
    intent.putExtra("NOTIFICATION_INTENT",
            PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0));
    context.startService(intent);
}

From source file:com.avalond.ad_blocak.main.StartFragment.java

private void startService() {
    Log.i(TAG, "Attempting to connect");
    Intent intent = VpnService.prepare(getContext());
    if (intent != null) {
        startActivityForResult(intent, REQUEST_START_VPN);
    } else {//from   w w w .jav  a 2  s . c o  m
        onActivityResult(REQUEST_START_VPN, RESULT_OK, null);
    }
}

From source file:com.intercepter.LocalVPN.java

private void startVPN() {
    Intent vpnIntent = VpnService.prepare(this);
    if (vpnIntent != null)
        startActivityForResult(vpnIntent, VPN_REQUEST_CODE);
    else//from   w ww. j  a v a  2 s. c o  m
        onActivityResult(VPN_REQUEST_CODE, RESULT_OK, null);
}

From source file:org.strongswan.android.ui.VpnProfileControlActivity.java

/**
 * Prepare the VpnService. If this succeeds the current VPN profile is
 * started./*from w w  w . ja  va 2s  .c om*/
 *
 * @param profileInfo a bundle containing the information about the profile to be started
 */
protected void prepareVpnService(Bundle profileInfo) {
    Intent intent;

    if (mWaitingForResult) {
        mProfileInfo = profileInfo;
        return;
    }

    try {
        intent = VpnService.prepare(this);
    } catch (IllegalStateException ex) {
        /* this happens if the always-on VPN feature (Android 4.2+) is activated */
        VpnNotSupportedError.showWithMessage(this, R.string.vpn_not_supported_during_lockdown);
        return;
    } catch (NullPointerException ex) {
        /* not sure when this happens exactly, but apparently it does */
        VpnNotSupportedError.showWithMessage(this, R.string.vpn_not_supported);
        return;
    }
    /* store profile info until the user grants us permission */
    mProfileInfo = profileInfo;
    if (intent != null) {
        try {
            mWaitingForResult = true;
            startActivityForResult(intent, PREPARE_VPN_SERVICE);
        } catch (ActivityNotFoundException ex) {
            /* it seems some devices, even though they come with Android 4,
             * don't have the VPN components built into the system image.
             * com.android.vpndialogs/com.android.vpndialogs.ConfirmDialog
             * will not be found then */
            VpnNotSupportedError.showWithMessage(this, R.string.vpn_not_supported);
            mWaitingForResult = false;
        }
    } else { /* user already granted permission to use VpnService */
        onActivityResult(PREPARE_VPN_SERVICE, RESULT_OK, null);
    }
}

From source file:de.flyingsnail.ipv6droid.android.MainActivity.java

/**
 * Start the system-managed setup of VPN
 * @param view supplied by GUI invocation
 *//*  w w  w .j  a  v  a  2s  .c o m*/
public void startVPN(View view) {
    // Start system-managed intent for VPN
    Intent systemVpnIntent = VpnService.prepare(getApplicationContext());
    if (systemVpnIntent != null) {
        startActivityForResult(systemVpnIntent, REQUEST_START_VPN);
    } else {
        onActivityResult(REQUEST_START_VPN, RESULT_OK, null);
    }
}

From source file:org.strongswan.android.ui.MainActivity.java

/**
 * Prepare the VpnService. If this succeeds the current VPN profile is
 * started./*ww  w  .  j  a va2s  . c  o  m*/
 *
 * @param profileInfo a bundle containing the information about the profile to be started
 */
protected void prepareVpnService(Bundle profileInfo) {
    Intent intent;
    try {
        intent = VpnService.prepare(this);
    } catch (IllegalStateException ex) {
        /* this happens if the always-on VPN feature (Android 4.2+) is activated */
        VpnNotSupportedError.showWithMessage(this, R.string.vpn_not_supported_during_lockdown);
        return;
    }
    /* store profile info until the user grants us permission */
    mProfileInfo = profileInfo;
    if (intent != null) {
        try {
            startActivityForResult(intent, PREPARE_VPN_SERVICE);
        } catch (ActivityNotFoundException ex) {
            /* it seems some devices, even though they come with Android 4,
             * don't have the VPN components built into the system image.
             * com.android.vpndialogs/com.android.vpndialogs.ConfirmDialog
             * will not be found then */
            VpnNotSupportedError.showWithMessage(this, R.string.vpn_not_supported);
        }
    } else { /* user already granted permission to use VpnService */
        onActivityResult(PREPARE_VPN_SERVICE, RESULT_OK, null);
    }
}

From source file:org.strongswan.android.ui.activity.MainActivity.java

/**
 * Prepare the VpnService. If this succeeds the current VPN profile is
 * started./*from   w w  w.ja  v  a2  s . c  o m*/
 *
 * @param profileInfo a bundle containing the information about the profile to be started
 */
protected void prepareVpnService(Bundle profileInfo) {
    Intent intent;
    try {
        intent = VpnService.prepare(this);
    } catch (IllegalStateException ex) {
        /* this happens if the always-on VPN feature (Android 4.2+) is activated */
        VpnNotSupportedError.showWithMessage(this, R.string.vpn_not_supported_during_lockdown);
        return;
    }
    /* store profile info until the user grants us permission */
    mProfileInfo = profileInfo;
    if (intent != null) {
        try {
            startActivityForResult(intent, PREPARE_VPN_SERVICE);
        } catch (ActivityNotFoundException ex) {
            /* it seems some devices, even though they come with Android 4,
             * don't have the VPN components built into the system image.
            * com.android.vpndialogs/com.android.vpndialogs.ConfirmDialog
            * will not be found then */
            VpnNotSupportedError.showWithMessage(this, R.string.vpn_not_supported);
        }
    } else { /* user already granted permission to use VpnService */
        onActivityResult(PREPARE_VPN_SERVICE, RESULT_OK, null);
    }
}

From source file:org.wso2.emm.agent.AlertActivity.java

/**
 * This method starts a VPN connection./*from w w  w. j a v a 2  s.  c  o m*/
 */
private void startVpn() {

    try {
        JSONObject vpnData = new JSONObject(payload);
        if (!vpnData.isNull(resources.getString(R.string.intent_extra_server))) {
            serverAddress = (String) vpnData.get(resources.getString(R.string.intent_extra_server));
        }
        if (!vpnData.isNull(resources.getString(R.string.intent_extra_server_port))) {
            serverPort = (String) vpnData.get(resources.getString(R.string.intent_extra_server_port));
        }

        if (!vpnData.isNull(resources.getString(R.string.intent_extra_shared_secret))) {
            sharedSecret = (String) vpnData.get(resources.getString(R.string.intent_extra_shared_secret));
        }

        if (!vpnData.isNull(resources.getString(R.string.intent_extra_dns))) {
            dnsServer = (String) vpnData.get(resources.getString(R.string.intent_extra_dns));
        }
    } catch (JSONException e) {
        Log.e(TAG, "Invalid VPN payload " + e);
    }

    Intent intent = VpnService.prepare(this);
    if (intent != null) {
        startActivityForResult(intent, VPN_REQUEST_CODE);
    } else {
        onActivityResult(VPN_REQUEST_CODE, RESULT_OK, null);
    }
}

From source file:eu.faircode.adblocker.ActivityMain.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.i(TAG, "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this));
    Util.logExtras(getIntent());// ww w . j a v  a  2 s. c  om

    if (Build.VERSION.SDK_INT < MIN_SDK) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.android);
        return;
    }

    Util.setTheme(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    swEnabled = (SwitchCompat) findViewById(R.id.swEnabled);
    running = true;

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean enabled = prefs.getBoolean("enabled", false);
    boolean initialized = prefs.getBoolean("initialized", false);

    // Upgrade
    Receiver.upgrade(initialized, this);

    if (!getIntent().hasExtra(EXTRA_APPROVE)) {
        if (enabled)
            ServiceSinkhole.start("UI", this);
        else
            ServiceSinkhole.stop("UI", this);
    }

    // Action bar
    final View actionView = getLayoutInflater().inflate(R.layout.actionmain, null, false);
    ivIcon = (ImageView) actionView.findViewById(R.id.ivIcon);
    ivQueue = (ImageView) actionView.findViewById(R.id.ivQueue);

    ivMetered = (ImageView) actionView.findViewById(R.id.ivMetered);

    // Icon
    ivIcon.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            menu_about();
            return true;
        }
    });

    // Title
    getSupportActionBar().setTitle(null);

    // Netguard is busy
    ivQueue.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            int location[] = new int[2];
            actionView.getLocationOnScreen(location);
            Toast toast = Toast.makeText(ActivityMain.this, R.string.msg_queue, Toast.LENGTH_LONG);
            toast.setGravity(Gravity.TOP | Gravity.START, location[0] + ivQueue.getLeft(),
                    Math.round(location[1] + ivQueue.getBottom() - toast.getView().getPaddingTop()));
            toast.show();
            return true;
        }
    });

    // On/off switch
    swEnabled.setChecked(enabled);
    swEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            Log.i(TAG, "Switch=" + isChecked);
            prefs.edit().putBoolean("enabled", isChecked).apply();

            if (isChecked) {
                try {
                    final Intent prepare = VpnService.prepare(ActivityMain.this);
                    if (prepare == null) {
                        Log.i(TAG, "Prepare done");
                        onActivityResult(REQUEST_VPN, RESULT_OK, null);
                    } else {
                        // Show dialog
                        LayoutInflater inflater = LayoutInflater.from(ActivityMain.this);
                        View view = inflater.inflate(R.layout.vpn, null, false);
                        dialogVpn = new AlertDialog.Builder(ActivityMain.this).setView(view)
                                .setCancelable(false)
                                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (running) {
                                            Log.i(TAG, "Start intent=" + prepare);
                                            try {
                                                startActivityForResult(prepare, REQUEST_VPN);
                                            } catch (Throwable ex) {
                                                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                                                Util.sendCrashReport(ex, ActivityMain.this);
                                                onActivityResult(REQUEST_VPN, RESULT_CANCELED, null);
                                                prefs.edit().putBoolean("enabled", false).apply();
                                            }
                                        }
                                    }
                                }).setOnDismissListener(new DialogInterface.OnDismissListener() {
                                    @Override
                                    public void onDismiss(DialogInterface dialogInterface) {
                                        dialogVpn = null;
                                    }
                                }).create();
                        dialogVpn.show();
                    }
                } catch (Throwable ex) {
                    // Prepare failed
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    Util.sendCrashReport(ex, ActivityMain.this);
                    prefs.edit().putBoolean("enabled", false).apply();
                }

            } else
                ServiceSinkhole.stop("switch off", ActivityMain.this);
        }
    });
    if (enabled)
        checkDoze();

    // Network is metered
    ivMetered.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            int location[] = new int[2];
            actionView.getLocationOnScreen(location);
            Toast toast = Toast.makeText(ActivityMain.this, R.string.msg_metered, Toast.LENGTH_LONG);
            toast.setGravity(Gravity.TOP | Gravity.START, location[0] + ivMetered.getLeft(),
                    Math.round(location[1] + ivMetered.getBottom() - toast.getView().getPaddingTop()));
            toast.show();
            return true;
        }
    });

    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setCustomView(actionView);

    // Disabled warning
    TextView tvDisabled = (TextView) findViewById(R.id.tvDisabled);
    tvDisabled.setVisibility(enabled ? View.GONE : View.VISIBLE);

    // Application list
    //        RecyclerView rvApplication = (RecyclerView) findViewById(R.id.rvApplication);
    //        rvApplication.setHasFixedSize(true);
    //        rvApplication.setLayoutManager(new LinearLayoutManager(this));
    //        adapter = new AdapterRule(this);
    //        rvApplication.setAdapter(adapter);

    // Swipe to refresh
    TypedValue tv = new TypedValue();
    getTheme().resolveAttribute(R.attr.colorPrimary, tv, true);
    //        swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefresh);
    //        swipeRefresh.setColorSchemeColors(Color.WHITE, Color.WHITE, Color.WHITE);
    //        swipeRefresh.setProgressBackgroundColorSchemeColor(tv.data);
    //        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
    //            @Override
    //            public void onRefresh() {
    //                Rule.clearCache(ActivityMain.this);
    //                ServiceSinkhole.reload("pull", ActivityMain.this);
    //                updateApplicationList(null);
    //            }
    //        });

    // Listen for preference changes
    prefs.registerOnSharedPreferenceChangeListener(this);

    // Listen for rule set changes
    IntentFilter ifr = new IntentFilter(ACTION_RULES_CHANGED);
    LocalBroadcastManager.getInstance(this).registerReceiver(onRulesChanged, ifr);

    // Listen for queue changes
    IntentFilter ifq = new IntentFilter(ACTION_QUEUE_CHANGED);
    LocalBroadcastManager.getInstance(this).registerReceiver(onQueueChanged, ifq);

    // Listen for added/removed applications
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
    intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
    intentFilter.addDataScheme("package");
    registerReceiver(packageChangedReceiver, intentFilter);

    // First use
    if (!initialized) {
        // Create view
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.first, null, false);
        TextView tvFirst = (TextView) view.findViewById(R.id.tvFirst);
        tvFirst.setMovementMethod(LinkMovementMethod.getInstance());

        // Show dialog
        dialogFirst = new AlertDialog.Builder(this).setView(view).setCancelable(false)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (running)
                            prefs.edit().putBoolean("initialized", true).apply();
                    }
                }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (running)
                            finish();
                    }
                }).setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {
                        dialogFirst = null;
                    }
                }).create();
        dialogFirst.show();
    }

    // Fill application list
    updateApplicationList(getIntent().getStringExtra(EXTRA_SEARCH));

    // Update IAB SKUs
    try {
        iab = new IAB(new IAB.Delegate() {
            @Override
            public void onReady(IAB iab) {
                try {
                    iab.updatePurchases();

                    if (!IAB.isPurchased(ActivityPro.SKU_LOG, ActivityMain.this))
                        prefs.edit().putBoolean("log", false).apply();
                    if (!IAB.isPurchased(ActivityPro.SKU_THEME, ActivityMain.this)) {
                        if (!"teal".equals(prefs.getString("theme", "teal")))
                            prefs.edit().putString("theme", "teal").apply();
                    }
                    if (!IAB.isPurchased(ActivityPro.SKU_SPEED, ActivityMain.this))
                        prefs.edit().putBoolean("show_stats", false).apply();
                } catch (Throwable ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                } finally {
                    iab.unbind();
                }
            }
        }, this);
        iab.bind();
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    checkExtras(getIntent());
}