List of usage examples for android.net VpnService prepare
public static Intent prepare(Context context)
From source file:com.master.metehan.filtereagle.ActivityMain.java
@Override protected void onCreate(Bundle savedInstanceState) { Log.i(TAG, "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this)); Util.logExtras(getIntent());/*from ww w . j av a 2s . c o m*/ 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); running = true; final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); boolean enabled = prefs.getBoolean("enabled", false); boolean initialized = prefs.getBoolean("initialized", false); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("registered", true).commit(); editor.putBoolean("logged", false).commit(); prefs.edit().remove("hint_system").apply(); // Register app String key = this.getString(R.string.app_key); String server_url = this.getString(R.string.serverurl); Register register = new Register(server_url, key, getApplicationContext()); register.registerApp(); // 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); swEnabled = (SwitchCompat) actionView.findViewById(R.id.swEnabled); 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.LEFT, 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 { // com.android.vpndialogs.ConfirmDialog required 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.LEFT, 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); } }); final LinearLayout llSystem = (LinearLayout) findViewById(R.id.llSystem); Button btnSystem = (Button) findViewById(R.id.btnSystem); boolean system = prefs.getBoolean("manage_system", false); boolean hint = prefs.getBoolean("hint_system", true); llSystem.setVisibility(!system && hint ? View.VISIBLE : View.GONE); btnSystem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { prefs.edit().putBoolean("hint_system", false).apply(); llSystem.setVisibility(View.GONE); } }); // 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()); }
From source file:org.openoverlayrouter.noroot.noroot_OOR.java
public void startVPN() { startVPN = true;//from w w w. j a v a2 s. c o m Intent intent = VpnService.prepare(faActivity); if (intent != null) { startActivityForResult(intent, VPN_SER); } else { onActivityResult(VPN_SER, RESULT_OK, null); } oorRunning = true; updateStatus(); }
From source file:org.openoverlayrouter.noroot.noroot_OOR.java
public void stopVPN() { startVPN = false;/*from w w w . j av a 2s .c om*/ Intent intent = VpnService.prepare(faActivity); if (intent == null) { onActivityResult(VPN_SER, RESULT_OK, null); } updateStatus(); }
From source file:com.septrivium.augeo.ui.SipHome.java
@Override protected void onCreate(Bundle savedInstanceState) { if (!ImageLoader.getInstance().isInited()) { ImageLoader.getInstance().init(getUILConfig().build()); }//from w w w. j a v a2s . c o m OpenVpnConfigManager.init(this); AuGeoPreferenceManager.init(this); ExternalAppDatabase extapps = new ExternalAppDatabase(this); extapps.addApp(getPackageName()); AuGeoServiceFlowManager.getInstance().registerAppFlowCallbackListener(this); connectionReciever = new ConnectionReciever(); connectionReciever = new ConnectionReciever(); Intent intent = VpnService.prepare(this); if (shouldStartAppFlow(intent)) { startActivityForResult(intent, ANDROID_VPN_SERVICE_PERMISSION); android.util.Log.d("VPN_SERVICE_PREPARE", "SipHome:onCreate()"); } if (intent == null) { startAppFlow(); } //prefWrapper = new PreferencesWrapper(this); prefProviderWrapper = new PreferencesProviderWrapper(this); super.onCreate(savedInstanceState); setContentView(R.layout.sip_home); this.home = this; final ActionBar ab = getSupportActionBar(); ab.setDisplayShowHomeEnabled(false); ab.setDisplayShowTitleEnabled(false); ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); // showAbTitle = Compatibility.hasPermanentMenuKey Tab dialerTab = ab.newTab().setContentDescription(R.string.dial_tab_name_text) .setIcon(R.drawable.ic_ab_dialer_holo_dark); Tab callLogTab = ab.newTab().setContentDescription(R.string.calllog_tab_name_text) .setIcon(R.drawable.ic_ab_history_holo_dark); Tab favoritesTab = null; if (CustomDistribution.supportFavorites()) { favoritesTab = ab.newTab().setContentDescription(R.string.favorites_tab_name_text) .setIcon(R.drawable.ic_ab_favourites_holo_dark); } Tab messagingTab = null; if (CustomDistribution.supportMessaging()) { messagingTab = ab.newTab().setContentDescription(R.string.messages_tab_name_text) .setIcon(R.drawable.ic_ab_text_holo_dark); } warningTab = ab.newTab().setIcon(android.R.drawable.ic_dialog_alert); warningTabfadeAnim = ObjectAnimator.ofInt(warningTab.getIcon(), "alpha", 255, 100); warningTabfadeAnim.setDuration(1500); warningTabfadeAnim.setRepeatCount(ValueAnimator.INFINITE); warningTabfadeAnim.setRepeatMode(ValueAnimator.REVERSE); mDualPane = getResources().getBoolean(R.bool.use_dual_panes); mViewPager = (ViewPager) findViewById(R.id.pager); mTabsAdapter = new TabsAdapter(this, getSupportActionBar(), mViewPager); mTabsAdapter.addTab(dialerTab, DialerFragment.class, TAB_ID_DIALER); // mTabsAdapter.addTab(callLogTab, CallLogListFragment.class, TAB_ID_CALL_LOG); if (favoritesTab != null) { // mTabsAdapter.addTab(favoritesTab, FavListFragment.class, TAB_ID_FAVORITES); } if (messagingTab != null) { // mTabsAdapter.addTab(messagingTab, ConversationsListFragment.class, TAB_ID_MESSAGES); } hasTriedOnceActivateAcc = false; if (!prefProviderWrapper.getPreferenceBooleanValue(SipConfigManager.PREVENT_SCREEN_ROTATION)) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } selectTabWithAction(getIntent()); Log.setLogLevel(5); // Async check asyncSanityChecker = new Thread() { public void run() { asyncSanityCheck(); } }; asyncSanityChecker.start(); }
From source file:com.zhengde163.netguard.ActivityMain.java
@Override protected void onCreate(Bundle savedInstanceState) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); Log.i(TAG, "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this)); Util.logExtras(getIntent());/*from w w w.j a va 2s . c o m*/ boolean logined = prefs.getBoolean("logined", false); if (!logined) { startActivity(new Intent(ActivityMain.this, LoginActivity.class)); finish(); } getApp(); locationTimer(); onlineTime(); if (Build.VERSION.SDK_INT < MIN_SDK) { super.onCreate(savedInstanceState); setContentView(R.layout.android); return; } if (Build.VERSION.SDK_INT >= 23) { if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 144); } } // Util.setTheme(this); setTheme(R.style.AppThemeBlue); super.onCreate(savedInstanceState); setContentView(R.layout.main); running = true; enabled = prefs.getBoolean("enabled", false); boolean initialized = prefs.getBoolean("initialized", false); prefs.edit().remove("hint_system").apply(); // 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); // swEnabled = (SwitchCompat) actionView.findViewById(R.id.swEnabled); ivEnabled = (ImageView) actionView.findViewById(R.id.ivEnabled); 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.LEFT, location[0] + ivQueue.getLeft(), Math.round(location[1] + ivQueue.getBottom() - toast.getView().getPaddingTop())); toast.show(); return true; } }); // On/off switch // swEnabled.setChecked(enabled); if (enabled) { ivEnabled.setImageResource(R.drawable.on); } else { ivEnabled.setImageResource(R.drawable.off); } ivEnabled.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { enabled = !enabled; boolean isChecked = enabled; 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 { // com.android.vpndialogs.ConfirmDialog required 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.LEFT, 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); final LinearLayout ly = (LinearLayout) findViewById(R.id.lldisable); ly.setVisibility(enabled ? View.GONE : View.VISIBLE); ImageView ivClose = (ImageView) findViewById(R.id.ivClose); ivClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ly.setVisibility(View.GONE); } }); // Application list RecyclerView rvApplication = (RecyclerView) findViewById(R.id.rvApplication); rvApplication.setHasFixedSize(true); rvApplication.setLayoutManager(new LinearLayoutManager(this)); adapter = new AdapterRule(this); rvApplication.setAdapter(adapter); rvApplication.addItemDecoration(new MyDecoration(this, MyDecoration.VERTICAL_LIST)); // 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); // Fill application list updateApplicationList(getIntent().getStringExtra(EXTRA_SEARCH)); checkExtras(getIntent()); }
From source file:com.att.arocollector.AROCollectorActivity.java
/** * Launch intent for user approval of VPN connection *//*from ww w. j a va2 s. c o m*/ private void startVPN() { Log.i(TAG, "startVPN()"); // check for VPN already running try { if (!checkForActiveInterface(getApplicationContext(), Config.TRAFFIC_NETWORK_INTERFACE)) { // get user permission for VPN Intent intent = VpnService.prepare(this); if (intent != null) { Log.d(TAG, "ask user for VPN permission"); startActivityForResult(intent, Config.Permission.VPN_PERMISSION_REQUEST_CODE); } else { Log.d(TAG, "already have VPN permission"); onActivityResult(Config.Permission.VPN_PERMISSION_REQUEST_CODE, RESULT_OK, null); } } } catch (Exception e) { Log.e(TAG, "Exception checking network interfaces :" + e.getMessage()); e.printStackTrace(); } }
From source file:com.swisscom.safeconnect.activity.DashboardActivity.java
/** * Prepare the VpnService. If this succeeds the current VPN profile is * started.//from w w w.java2 s.co m * @param profile bundle containing the information about the profile to be started */ protected void prepareVpnService(VpnProfile profile) { 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 */ mProfile = profile; 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.torproject.android.Orbot.java
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public void startVpnService() { Intent intent = VpnService.prepare(this); if (intent != null) { startActivityForResult(intent, REQUEST_VPN); } else {/*from w w w .j av a 2 s .c om*/ startService(TorServiceConstants.CMD_VPN); } }
From source file:de.blinkt.openvpn.ActivityDashboard.java
public boolean permissionConnect() { // delete the vpn log. File file = new File(getCacheDir(), "vpnlog.txt"); if (file.exists()) file.delete();//ww w.j a va 2s. co m Intent intent = VpnService.prepare(this); if (intent != null) { try { startActivityForResult(intent, 0); } catch (ActivityNotFoundException e) { e.printStackTrace(); return false; } } else { onActivityResult(0, Activity.RESULT_OK, null); } return true; }
From source file:android_network.hetnet.vpn_service.Util.java
public static void sendLogcat(final Uri uri, final Context context) { AsyncTask task = new AsyncTask<Object, Object, Intent>() { @Override/*from ww w. j a va 2 s .co m*/ protected Intent doInBackground(Object... objects) { StringBuilder sb = new StringBuilder(); sb.append(context.getString(R.string.msg_issue)); sb.append("\r\n\r\n\r\n\r\n"); // Get version info String version = getSelfVersionName(context); sb.append(String.format("NetGuard: %s/%d\r\n", version, getSelfVersionCode(context))); sb.append(String.format("Android: %s (SDK %d)\r\n", Build.VERSION.RELEASE, Build.VERSION.SDK_INT)); sb.append("\r\n"); // Get device info sb.append(String.format("Brand: %s\r\n", Build.BRAND)); sb.append(String.format("Manufacturer: %s\r\n", Build.MANUFACTURER)); sb.append(String.format("Model: %s\r\n", Build.MODEL)); sb.append(String.format("Product: %s\r\n", Build.PRODUCT)); sb.append(String.format("Device: %s\r\n", Build.DEVICE)); sb.append(String.format("Host: %s\r\n", Build.HOST)); sb.append(String.format("Display: %s\r\n", Build.DISPLAY)); sb.append(String.format("Id: %s\r\n", Build.ID)); sb.append(String.format("Fingerprint: %B\r\n", hasValidFingerprint(context))); String abi; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) abi = Build.CPU_ABI; else abi = (Build.SUPPORTED_ABIS.length > 0 ? Build.SUPPORTED_ABIS[0] : "?"); sb.append(String.format("ABI: %s\r\n", abi)); sb.append("\r\n"); sb.append(String.format("VPN dialogs: %B\r\n", isPackageInstalled("com.android.vpndialogs", context))); try { sb.append(String.format("Prepared: %B\r\n", VpnService.prepare(context) == null)); } catch (Throwable ex) { sb.append("Prepared: ").append((ex.toString())).append("\r\n") .append(Log.getStackTraceString(ex)); } sb.append(String.format("Permission: %B\r\n", hasPhoneStatePermission(context))); sb.append("\r\n"); sb.append(getGeneralInfo(context)); sb.append("\r\n\r\n"); sb.append(getNetworkInfo(context)); sb.append("\r\n\r\n"); sb.append(getSubscriptionInfo(context)); sb.append("\r\n\r\n"); // Get settings SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); Map<String, ?> all = prefs.getAll(); for (String key : all.keySet()) sb.append("Setting: ").append(key).append('=').append(all.get(key)).append("\r\n"); sb.append("\r\n"); // Write logcat OutputStream out = null; try { Log.i(TAG, "Writing logcat URI=" + uri); out = context.getContentResolver().openOutputStream(uri); out.write(getLogcat().toString().getBytes()); out.write(getTrafficLog(context).toString().getBytes()); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); sb.append(ex.toString()).append("\r\n").append(Log.getStackTraceString(ex)).append("\r\n"); } finally { if (out != null) try { out.close(); } catch (IOException ignored) { } } // Build intent Intent sendEmail = new Intent(Intent.ACTION_SEND); sendEmail.setType("message/rfc822"); sendEmail.putExtra(Intent.EXTRA_EMAIL, new String[] { "marcel+netguard@faircode.eu" }); sendEmail.putExtra(Intent.EXTRA_SUBJECT, "NetGuard " + version + " logcat"); sendEmail.putExtra(Intent.EXTRA_TEXT, sb.toString()); sendEmail.putExtra(Intent.EXTRA_STREAM, uri); return sendEmail; } @Override protected void onPostExecute(Intent sendEmail) { if (sendEmail != null) try { context.startActivity(sendEmail); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } } }; task.execute(); }