2 * Copyright 2015-2016 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
6 * Privacy Browser is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * Privacy Browser is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
20 package com.stoutner.privacybrowser;
22 import android.annotation.SuppressLint;
23 import android.app.Activity;
24 import android.app.DownloadManager;
25 import android.content.Intent;
26 import android.content.SharedPreferences;
27 import android.content.res.Configuration;
28 import android.graphics.Bitmap;
29 import android.net.Uri;
30 import android.os.Build;
31 import android.os.Bundle;
32 import android.preference.PreferenceManager;
33 import android.support.design.widget.NavigationView;
34 import android.support.design.widget.Snackbar;
35 import android.support.v4.app.DialogFragment;
36 import android.support.v4.view.GravityCompat;
37 import android.support.v4.widget.DrawerLayout;
38 import android.support.v4.widget.SwipeRefreshLayout;
39 import android.support.v7.app.ActionBar;
40 import android.support.v7.app.ActionBarDrawerToggle;
41 import android.support.v7.app.AppCompatActivity;
42 import android.support.v7.app.AppCompatDialogFragment;
43 import android.support.v7.widget.Toolbar;
44 import android.util.Patterns;
45 import android.view.KeyEvent;
46 import android.view.Menu;
47 import android.view.MenuItem;
48 import android.view.View;
49 import android.view.inputmethod.InputMethodManager;
50 import android.webkit.CookieManager;
51 import android.webkit.DownloadListener;
52 import android.webkit.WebChromeClient;
53 import android.webkit.WebStorage;
54 import android.webkit.WebView;
55 import android.webkit.WebViewClient;
56 import android.widget.EditText;
57 import android.widget.FrameLayout;
58 import android.widget.ImageView;
59 import android.widget.ProgressBar;
61 import java.io.UnsupportedEncodingException;
62 import java.net.MalformedURLException;
64 import java.net.URLEncoder;
66 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
67 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener {
68 // favoriteIcon is public static so it can be accessed from CreateHomeScreenShortcut.
69 public static Bitmap favoriteIcon;
70 // mainWebView is public static so it can be accessed from AboutDialog. It is also used in onCreate(), onOptionsItemSelected(), onNavigationItemSelected(), and loadUrlFromTextBox().
71 public static WebView mainWebView;
73 // drawerToggle is used in onCreate(), onPostCreate(), onConfigurationChanged(), onNewIntent(), and onNavigationItemSelected().
74 private ActionBarDrawerToggle drawerToggle;
75 // drawerLayout is used in onCreate(), onNewIntent(), and onBackPressed().
76 private DrawerLayout drawerLayout;
77 // mainMenu is used in onCreateOptionsMenu() and onOptionsItemSelected().
78 private Menu mainMenu;
79 // formattedUrlString is used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
80 private String formattedUrlString;
81 // homepage is used in onCreate() and onOptionsItemSelected().
82 private String homepage;
83 // javaScriptEnabled is used in onCreate(), onCreateOptionsMenu(), onOptionsItemSelected(), and loadUrlFromTextBox().
84 private boolean javaScriptEnabled;
85 // domStorageEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
86 private boolean domStorageEnabled;
88 /* saveFormDataEnabled does nothing until database storage is implemented.
89 // saveFormDataEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
90 private boolean saveFormDataEnabled;
93 // cookieManager is used in onCreate(), onOptionsItemSelected(), and onNavigationItemSelected().
94 private CookieManager cookieManager;
95 // firstPartyCookiesEnabled is used in onCreate(), onCreateOptionsMenu(), onPrepareOptionsMenu(), and onOptionsItemSelected().
96 private boolean firstPartyCookiesEnabled;
97 // thirdPartyCookiesEnabled is uesd in onCreate(), onCreateOptionsMenu(), onPrepareOptionsMenu(), and onOptionsItemSelected().
98 private boolean thirdPartyCookiesEnabled;
100 // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
101 private EditText urlTextBox;
104 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled. The whole premise of Privacy Browser is built around an understanding of these dangers.
105 @SuppressLint("SetJavaScriptEnabled")
106 protected void onCreate(Bundle savedInstanceState) {
107 super.onCreate(savedInstanceState);
108 setContentView(R.layout.coordinator_layout);
110 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
111 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
112 setSupportActionBar(supportAppBar);
114 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
116 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
117 final ActionBar appBar = getSupportActionBar();
119 // Setup AdView for the free flavor.
120 final View adView = findViewById(R.id.adView);
122 // Implement swipe to refresh
123 final SwipeRefreshLayout swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
124 swipeToRefresh.setColorSchemeResources(R.color.blue);
125 swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
127 public void onRefresh() {
128 mainWebView.reload();
132 mainWebView = (WebView) findViewById(R.id.mainWebView);
134 if (appBar != null) {
135 // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
136 appBar.setCustomView(R.layout.url_bar);
137 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
139 // Set the "go" button on the keyboard to load the URL in urlTextBox.
140 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
141 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
142 public boolean onKey(View v, int keyCode, KeyEvent event) {
143 // If the event is a key-down event on the "enter" button, load the URL.
144 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
145 // Load the URL into the mainWebView and consume the event.
147 loadUrlFromTextBox();
148 } catch (UnsupportedEncodingException e) {
151 // If the enter key was pressed, consume the event.
154 // If any other key was pressed, do not consume the event.
161 // Create the navigation drawer.
162 drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
163 // The DrawerTitle identifies the drawer in accessibility mode.
164 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
166 // Listen for touches on the navigation menu.
167 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
168 navigationView.setNavigationItemSelectedListener(this);
170 // drawerToggle creates the hamburger icon at the start of the AppBar.
171 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
173 mainWebView.setWebViewClient(new WebViewClient() {
174 // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
176 public boolean shouldOverrideUrlLoading(WebView view, String url) {
177 mainWebView.loadUrl(url);
181 // Update the URL in urlTextBox when the page starts to load.
183 public void onPageStarted(WebView view, String url, Bitmap favicon) {
184 urlTextBox.setText(url);
187 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
189 public void onPageFinished(WebView view, String url) {
190 formattedUrlString = url;
192 // Only update urlTextBox if the user is not typing in it.
193 if (!urlTextBox.hasFocus()) {
194 urlTextBox.setText(formattedUrlString);
199 mainWebView.setWebChromeClient(new WebChromeClient() {
200 // Update the progress bar when a page is loading.
202 public void onProgressChanged(WebView view, int progress) {
203 // Make sure that appBar is not null.
204 if (appBar != null) {
205 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
206 progressBar.setProgress(progress);
207 if (progress < 100) {
208 progressBar.setVisibility(View.VISIBLE);
210 progressBar.setVisibility(View.GONE);
212 //Stop the SwipeToRefresh indicator if it is running
213 swipeToRefresh.setRefreshing(false);
218 // Set the favorite icon when it changes.
220 public void onReceivedIcon(WebView view, Bitmap icon) {
221 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
224 // Place the favorite icon in the appBar if it is not null.
225 if (appBar != null) {
226 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
227 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
231 // Enter full screen video
233 public void onShowCustomView(View view, CustomViewCallback callback) {
234 if (appBar != null) {
238 // Show the fullScreenVideoFrameLayout.
239 fullScreenVideoFrameLayout.addView(view);
240 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
242 // Hide the mainWebView.
243 mainWebView.setVisibility(View.GONE);
245 // Hide the ad if this is the free flavor.
246 BannerAd.hideAd(adView);
248 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
249 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
250 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
253 // Set the one flag supported by API >= 14.
254 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
256 // Set the two flags that are supported by API >= 16.
257 if (Build.VERSION.SDK_INT >= 16) {
258 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
261 // Set all three flags that are supported by API >= 19.
262 if (Build.VERSION.SDK_INT >= 19) {
263 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
267 // Exit full screen video
268 public void onHideCustomView() {
269 if (appBar != null) {
273 // Show the mainWebView.
274 mainWebView.setVisibility(View.VISIBLE);
276 // Show the ad if this is the free flavor.
277 BannerAd.showAd(adView);
279 // Hide the fullScreenVideoFrameLayout.
280 fullScreenVideoFrameLayout.removeAllViews();
281 fullScreenVideoFrameLayout.setVisibility(View.GONE);
285 // Allow the downloading of files.
286 mainWebView.setDownloadListener(new DownloadListener() {
287 // Launch the Android download manager when a link leads to a download.
289 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
290 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
291 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
293 // Add the URL as the description for the download.
294 requestUri.setDescription(url);
296 // Show the download notification after the download is completed.
297 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
299 // Initiate the download and display a Snackbar.
300 downloadManager.enqueue(requestUri);
301 Snackbar.make(findViewById(R.id.mainWebView), R.string.download_started, Snackbar.LENGTH_SHORT).show();
305 // Allow pinch to zoom.
306 mainWebView.getSettings().setBuiltInZoomControls(true);
308 // Hide zoom controls.
309 mainWebView.getSettings().setDisplayZoomControls(false);
311 // Initialize the default preference values the first time the program is run.
312 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
314 // Get the shared preference values.
315 SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
317 // Set JavaScript initial status.
318 javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
319 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
321 // Initialize cookieManager.
322 cookieManager = CookieManager.getInstance();
324 // Set cookies initial status.
325 firstPartyCookiesEnabled = savedPreferences.getBoolean("first_party_cookies_enabled", false);
326 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
328 // Set third-party cookies initial status if API >= 21.
329 if (Build.VERSION.SDK_INT >= 21) {
330 thirdPartyCookiesEnabled = savedPreferences.getBoolean("third_party_cookies_enabled", false);
331 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
334 // Set DOM storage initial status.
335 domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
336 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
338 // Set homepage initial status.
339 homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
341 // Get the intent information that started the app.
342 final Intent intent = getIntent();
344 if (intent.getData() != null) {
345 // Get the intent data and convert it to a string.
346 final Uri intentUriData = intent.getData();
347 formattedUrlString = intentUriData.toString();
350 // If formattedUrlString is null assign the homepage to it.
351 if (formattedUrlString == null) {
352 formattedUrlString = homepage;
355 // Load the initial website.
356 mainWebView.loadUrl(formattedUrlString);
358 // Load the ad if this is the free flavor.
359 BannerAd.requestAd(adView);
363 protected void onNewIntent(Intent intent) {
364 // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
367 if (intent.getData() != null) {
368 // Get the intent data and convert it to a string.
369 final Uri intentUriData = intent.getData();
370 formattedUrlString = intentUriData.toString();
373 // Close the navigation drawer if it is open.
374 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
375 drawerLayout.closeDrawer(GravityCompat.START);
379 mainWebView.loadUrl(formattedUrlString);
381 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
382 mainWebView.requestFocus();
386 public boolean onCreateOptionsMenu(Menu menu) {
387 // Inflate the menu; this adds items to the action bar if it is present.
388 getMenuInflater().inflate(R.menu.menu_options, menu);
390 // Set mainMenu so it can be used by onOptionsItemSelected.
393 // Get MenuItems for checkable menu items.
394 MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
395 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
396 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
397 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
398 /* toggleSaveFormData does nothing until database storage is implemented.
399 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
402 // Set the initial icon for toggleJavaScript
403 if (javaScriptEnabled) {
404 toggleJavaScript.setIcon(R.drawable.javascript_enabled);
406 if (domStorageEnabled || firstPartyCookiesEnabled) {
407 toggleJavaScript.setIcon(R.drawable.warning);
409 toggleJavaScript.setIcon(R.drawable.privacy_mode);
413 // Set the initial status of the menu item checkboxes.
414 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
415 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
416 toggleDomStorage.setChecked(domStorageEnabled);
417 /* toggleSaveFormData does nothing until database storage is implemented.
418 toggleSaveFormData.setChecked(saveFormDataEnabled);
425 public boolean onPrepareOptionsMenu(Menu menu) {
426 // Only enable Third-Party Cookies if SDK >= 21 and First-Party Cookies are enabled.
427 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
428 if ((Build.VERSION.SDK_INT >= 21) && firstPartyCookiesEnabled) {
429 toggleThirdPartyCookies.setEnabled(true);
431 toggleThirdPartyCookies.setEnabled(false);
434 // Enable Clear Cookies if there are any.
435 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
436 clearCookies.setEnabled(cookieManager.hasCookies());
438 // Run all the other default commands.
439 super.onPrepareOptionsMenu(menu);
441 // return true displays the menu.
446 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
447 @SuppressLint("SetJavaScriptEnabled")
448 // removeAllCookies is deprecated, but it is required for API < 21.
449 @SuppressWarnings("deprecation")
450 public boolean onOptionsItemSelected(MenuItem menuItem) {
451 int menuItemId = menuItem.getItemId();
453 // Some options need to update the drawable for toggleJavaScript.
454 MenuItem toggleJavaScript = mainMenu.findItem(R.id.toggleJavaScript);
456 // Set the commands that relate to the menu entries.
457 switch (menuItemId) {
458 case R.id.toggleJavaScript:
459 if (javaScriptEnabled) {
460 javaScriptEnabled = false;
461 mainWebView.getSettings().setJavaScriptEnabled(false);
462 mainWebView.reload();
464 // Update the toggleJavaScript icon and display a snackbar.
465 if (domStorageEnabled || firstPartyCookiesEnabled) {
466 menuItem.setIcon(R.drawable.warning);
467 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
469 menuItem.setIcon(R.drawable.privacy_mode);
470 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
473 javaScriptEnabled = true;
474 menuItem.setIcon(R.drawable.javascript_enabled);
475 mainWebView.getSettings().setJavaScriptEnabled(true);
476 mainWebView.reload();
477 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
481 case R.id.toggleFirstPartyCookies:
482 if (firstPartyCookiesEnabled) {
483 firstPartyCookiesEnabled = false;
484 menuItem.setChecked(false);
485 cookieManager.setAcceptCookie(false);
486 mainWebView.reload();
488 // Update the toggleJavaScript icon if appropriate and display a snackbar.
489 if (!javaScriptEnabled) {
490 if (domStorageEnabled) {
491 toggleJavaScript.setIcon(R.drawable.warning);
492 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
494 toggleJavaScript.setIcon(R.drawable.privacy_mode);
495 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
498 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
501 firstPartyCookiesEnabled = true;
502 menuItem.setChecked(true);
503 cookieManager.setAcceptCookie(true);
504 mainWebView.reload();
506 // Update the toggleJavaScript icon if appropriate.
507 if (!javaScriptEnabled) {
508 toggleJavaScript.setIcon(R.drawable.warning);
509 } // Else do nothing because JavaScript is enabled.
511 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
515 case R.id.toggleThirdPartyCookies:
516 if (Build.VERSION.SDK_INT >= 21) {
517 if (thirdPartyCookiesEnabled) {
518 thirdPartyCookiesEnabled = false;
519 menuItem.setChecked(false);
520 cookieManager.setAcceptThirdPartyCookies(mainWebView, false);
521 mainWebView.reload();
523 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
525 thirdPartyCookiesEnabled = true;
526 menuItem.setChecked(true);
527 cookieManager.setAcceptThirdPartyCookies(mainWebView, true);
528 mainWebView.reload();
530 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
532 } // Else do nothing because SDK < 21.
535 case R.id.toggleDomStorage:
536 if (domStorageEnabled) {
537 domStorageEnabled = false;
538 menuItem.setChecked(false);
539 mainWebView.getSettings().setDomStorageEnabled(false);
540 mainWebView.reload();
542 // Update the toggleJavaScript icon if appropriate and display a snackbar.
543 if (!javaScriptEnabled) {
544 if (firstPartyCookiesEnabled) {
545 toggleJavaScript.setIcon(R.drawable.warning);
546 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
548 toggleJavaScript.setIcon(R.drawable.privacy_mode);
549 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
552 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
555 domStorageEnabled = true;
556 menuItem.setChecked(true);
557 mainWebView.getSettings().setDomStorageEnabled(true);
558 mainWebView.reload();
560 // Update the toggleJavaScript icon if appropriate.
561 if (!javaScriptEnabled) {
562 toggleJavaScript.setIcon(R.drawable.warning);
563 } // Else Do nothing because JavaScript is enabled.
565 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
569 case R.id.clearCookies:
570 if (Build.VERSION.SDK_INT < 21) {
571 cookieManager.removeAllCookie();
573 cookieManager.removeAllCookies(null);
575 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
578 case R.id.clearDomStorage:
579 WebStorage webStorage = WebStorage.getInstance();
580 webStorage.deleteAllData();
581 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
585 Intent shareIntent = new Intent();
586 shareIntent.setAction(Intent.ACTION_SEND);
587 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
588 shareIntent.setType("text/plain");
589 startActivity(Intent.createChooser(shareIntent, "Share URL"));
592 case R.id.addToHomescreen:
593 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
594 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
595 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
597 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
601 return super.onOptionsItemSelected(menuItem);
606 // removeAllCookies is deprecated, but it is required for API < 21.
607 @SuppressWarnings("deprecation")
608 public boolean onNavigationItemSelected(MenuItem menuItem) {
609 int menuItemId = menuItem.getItemId();
611 switch (menuItemId) {
613 mainWebView.loadUrl(homepage);
617 if (mainWebView.canGoBack()) {
618 mainWebView.goBack();
623 if (mainWebView.canGoForward()) {
624 mainWebView.goForward();
629 // Launch the system Download Manager.
630 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
632 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
633 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
635 startActivity(downloadManagerIntent);
639 // Launch PreferenceFragment.
640 Intent intent = new Intent(this, SettingsActivity.class);
641 startActivity(intent);
645 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
646 AppCompatDialogFragment aboutDialog = new AboutDialog();
647 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
650 case R.id.clearAndExit:
651 // Clear DOM storage.
652 WebStorage domStorage = WebStorage.getInstance();
653 domStorage.deleteAllData();
655 // Clear cookies. The commands changed slightly in API 21.
656 if (Build.VERSION.SDK_INT >= 21) {
657 cookieManager.removeAllCookies(null);
659 cookieManager.removeAllCookie();
662 // Destroy the internal state of the webview.
663 mainWebView.destroy();
665 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
666 if (Build.VERSION.SDK_INT >= 21) {
667 finishAndRemoveTask();
677 // Close the navigation drawer.
678 drawerLayout.closeDrawer(GravityCompat.START);
683 public void onPostCreate(Bundle savedInstanceState) {
684 super.onPostCreate(savedInstanceState);
686 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
687 drawerToggle.syncState();
691 public void onConfigurationChanged(Configuration newConfig) {
692 super.onConfigurationChanged(newConfig);
694 // Update the status of the drawerToggle icon.
695 drawerToggle.onConfigurationChanged(newConfig);
699 public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
700 // Do nothing because the user selected "Cancel".
704 public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
705 // Get shortcutNameEditText from the alert dialog.
706 EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
708 // Create the bookmark shortcut based on formattedUrlString.
709 Intent bookmarkShortcut = new Intent();
710 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
711 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
713 // Place the bookmark shortcut on the home screen.
714 Intent placeBookmarkShortcut = new Intent();
715 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
716 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
717 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
718 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
719 sendBroadcast(placeBookmarkShortcut);
722 // Override onBackPressed to handle the navigation drawer and mainWebView.
724 public void onBackPressed() {
725 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
727 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
728 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
729 drawerLayout.closeDrawer(GravityCompat.START);
731 // Load the previous URL if available.
732 if (mainWebView.canGoBack()) {
733 mainWebView.goBack();
735 // Pass onBackPressed to the system.
736 super.onBackPressed();
741 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
742 // Get the text from urlTextBox and convert it to a string.
743 String unformattedUrlString = urlTextBox.getText().toString();
744 URL unformattedUrl = null;
745 Uri.Builder formattedUri = new Uri.Builder();
747 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
748 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
749 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
750 if (!unformattedUrlString.startsWith("http")) {
751 unformattedUrlString = "http://" + unformattedUrlString;
754 // Convert unformattedUrlString to a URL, then to a URI, and then back to a string, which sanitizes the input and adds in any missing components.
756 unformattedUrl = new URL(unformattedUrlString);
757 } catch (MalformedURLException e) {
761 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
762 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
763 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
764 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
765 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
766 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
768 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
769 formattedUrlString = formattedUri.build().toString();
771 // Sanitize the search input and convert it to a DuckDuckGo search.
772 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
774 // Use the correct search URL based on javaScriptEnabled.
775 if (javaScriptEnabled) {
776 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
778 formattedUrlString = "https://duckduckgo.com/html/?q=" + encodedUrlString;
782 mainWebView.loadUrl(formattedUrlString);
784 // Hides the keyboard so we can see the webpage.
785 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
786 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);