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.DialogFragment;
25 import android.app.DownloadManager;
26 import android.content.Intent;
27 import android.content.SharedPreferences;
28 import android.content.res.Configuration;
29 import android.graphics.Bitmap;
30 import android.graphics.drawable.BitmapDrawable;
31 import android.graphics.drawable.Drawable;
32 import android.net.Uri;
33 import android.os.Build;
34 import android.os.Bundle;
35 import android.preference.PreferenceManager;
36 import android.support.design.widget.NavigationView;
37 import android.support.design.widget.Snackbar;
38 import android.support.v4.content.ContextCompat;
39 import android.support.v4.view.GravityCompat;
40 import android.support.v4.widget.DrawerLayout;
41 import android.support.v4.widget.SwipeRefreshLayout;
42 import android.support.v7.app.ActionBar;
43 import android.support.v7.app.ActionBarDrawerToggle;
44 import android.support.v7.app.AppCompatActivity;
45 import android.support.v7.widget.Toolbar;
46 import android.util.Patterns;
47 import android.view.KeyEvent;
48 import android.view.Menu;
49 import android.view.MenuItem;
50 import android.view.View;
51 import android.view.inputmethod.InputMethodManager;
52 import android.webkit.CookieManager;
53 import android.webkit.DownloadListener;
54 import android.webkit.WebChromeClient;
55 import android.webkit.WebStorage;
56 import android.webkit.WebView;
57 import android.webkit.WebViewClient;
58 import android.webkit.WebViewDatabase;
59 import android.widget.EditText;
60 import android.widget.FrameLayout;
61 import android.widget.ImageView;
62 import android.widget.ProgressBar;
64 import java.io.UnsupportedEncodingException;
65 import java.net.MalformedURLException;
67 import java.net.URLEncoder;
69 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
70 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener {
71 // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `BookmarksActivity`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
72 // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
73 public static Bitmap favoriteIcon;
75 // mainWebView is public static so it can be accessed from SettingsFragment.
76 // It is also used in onCreate(), onOptionsItemSelected(), onNavigationItemSelected(), and loadUrlFromTextBox().
77 public static WebView mainWebView;
79 // formattedUrlString is public static so it can be accessed from BookmarksActivity.
80 // It is also used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
81 public static String formattedUrlString;
83 // mainMenu is public static so it can be accessed from SettingsFragment. It is also used in onCreateOptionsMenu() and onOptionsItemSelected().
84 public static Menu mainMenu;
86 // cookieManager is public static so it can be accessed from SettingsFragment. It is also used in onCreate(), onOptionsItemSelected(), and onNavigationItemSelected().
87 public static CookieManager cookieManager;
89 // javaScriptEnabled is public static so it can be accessed from SettingsFragment.
90 // It is also used in onCreate(), onCreateOptionsMenu(), onOptionsItemSelected(), and loadUrlFromTextBox().
91 public static boolean javaScriptEnabled;
93 // firstPartyCookiesEnabled is public static so it can be accessed from SettingsFragment.
94 // It is also used in onCreate(), onCreateOptionsMenu(), onPrepareOptionsMenu(), and onOptionsItemSelected().
95 public static boolean firstPartyCookiesEnabled;
97 // thirdPartyCookiesEnabled is used in onCreate(), onCreateOptionsMenu(), onPrepareOptionsMenu(), and onOptionsItemSelected().
98 public static boolean thirdPartyCookiesEnabled;
100 // domStorageEnabled is public static so it can be accessed from SettingsFragment. It is also used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
101 public static boolean domStorageEnabled;
103 // saveFormDataEnabled is public static so it can be accessed from SettingsFragment. It is also used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
104 public static boolean saveFormDataEnabled;
106 // javaScriptDisabledSearchURL is public static so it can be accessed from SettingsFragment. It is also used in onCreate() and loadURLFromTextBox().
107 public static String javaScriptDisabledSearchURL;
109 // javaScriptEnabledSearchURL is public static so it can be accessed from SettingsFragment. It is also used in onCreate() and loadURLFromTextBox().
110 public static String javaScriptEnabledSearchURL;
112 // homepage is public static so it can be accessed from SettingsFragment. It is also used in onCreate() and onOptionsItemSelected().
113 public static String homepage;
115 // swipeToRefresh is public static so it can be accessed from SettingsFragment. It is also used in onCreate().
116 public static SwipeRefreshLayout swipeToRefresh;
118 // swipeToRefreshEnabled is public static so it can be accessed from SettingsFragment. It is also used in onCreate().
119 public static boolean swipeToRefreshEnabled;
123 // drawerToggle is used in onCreate(), onPostCreate(), onConfigurationChanged(), onNewIntent(), and onNavigationItemSelected().
124 private ActionBarDrawerToggle drawerToggle;
126 // drawerLayout is used in onCreate(), onNewIntent(), and onBackPressed().
127 private DrawerLayout drawerLayout;
129 // privacyIcon is used in onCreateOptionsMenu() and updatePrivacyIcon().
130 private MenuItem privacyIcon;
132 // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
133 private EditText urlTextBox;
135 // adView is used in onCreate() and onConfigurationChanged().
139 // 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.
140 @SuppressLint("SetJavaScriptEnabled")
141 protected void onCreate(Bundle savedInstanceState) {
142 super.onCreate(savedInstanceState);
143 setContentView(R.layout.main_coordinatorlayout);
145 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
146 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
147 setSupportActionBar(supportAppBar);
148 final ActionBar appBar = getSupportActionBar();
150 // This is needed to get rid of the Android Studio warning that appBar might be null.
151 assert appBar != null;
153 // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
154 appBar.setCustomView(R.layout.url_bar);
155 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
157 // Set the "go" button on the keyboard to load the URL in urlTextBox.
158 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
159 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
160 public boolean onKey(View v, int keyCode, KeyEvent event) {
161 // If the event is a key-down event on the "enter" button, load the URL.
162 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
163 // Load the URL into the mainWebView and consume the event.
165 loadUrlFromTextBox();
166 } catch (UnsupportedEncodingException e) {
169 // If the enter key was pressed, consume the event.
172 // If any other key was pressed, do not consume the event.
178 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
180 // Implement swipe to refresh
181 swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
182 assert swipeToRefresh != null; //This assert removes the incorrect warning on the following line that swipeToRefresh might be null.
183 swipeToRefresh.setColorSchemeResources(R.color.blue);
184 swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
186 public void onRefresh() {
187 mainWebView.reload();
191 mainWebView = (WebView) findViewById(R.id.mainWebView);
193 // Create the navigation drawer.
194 drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
195 // The DrawerTitle identifies the drawer in accessibility mode.
196 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
198 // Listen for touches on the navigation menu.
199 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
200 assert navigationView != null; // This assert removes the incorrect warning on the following line that navigationView might be null.
201 navigationView.setNavigationItemSelectedListener(this);
203 // drawerToggle creates the hamburger icon at the start of the AppBar.
204 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
206 mainWebView.setWebViewClient(new WebViewClient() {
207 // shouldOverrideUrlLoading makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
209 public boolean shouldOverrideUrlLoading(WebView view, String url) {
210 // Use an external email program if the link begins with "mailto:".
211 if (url.startsWith("mailto:")) {
212 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
213 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
215 // Parse the url and set it as the data for the `Intent`.
216 emailIntent.setData(Uri.parse(url));
218 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
219 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
222 startActivity(emailIntent);
224 } else { // Load the URL in Privacy Browser.
225 mainWebView.loadUrl(url);
230 // Update the URL in urlTextBox when the page starts to load.
232 public void onPageStarted(WebView view, String url, Bitmap favicon) {
233 urlTextBox.setText(url);
236 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
238 public void onPageFinished(WebView view, String url) {
239 formattedUrlString = url;
241 // Only update urlTextBox if the user is not typing in it.
242 if (!urlTextBox.hasFocus()) {
243 urlTextBox.setText(formattedUrlString);
248 mainWebView.setWebChromeClient(new WebChromeClient() {
249 // Update the progress bar when a page is loading.
251 public void onProgressChanged(WebView view, int progress) {
252 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
253 progressBar.setProgress(progress);
254 if (progress < 100) {
255 progressBar.setVisibility(View.VISIBLE);
257 progressBar.setVisibility(View.GONE);
259 //Stop the SwipeToRefresh indicator if it is running
260 swipeToRefresh.setRefreshing(false);
264 // Set the favorite icon when it changes.
266 public void onReceivedIcon(WebView view, Bitmap icon) {
267 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
270 // Place the favorite icon in the appBar.
271 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
272 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
275 // Enter full screen video
277 public void onShowCustomView(View view, CustomViewCallback callback) {
280 // Show the fullScreenVideoFrameLayout.
281 assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
282 fullScreenVideoFrameLayout.addView(view);
283 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
285 // Hide the mainWebView.
286 mainWebView.setVisibility(View.GONE);
288 // Hide the ad if this is the free flavor.
289 BannerAd.hideAd(adView);
291 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
292 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
293 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
295 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
298 // Exit full screen video
299 public void onHideCustomView() {
302 // Show the mainWebView.
303 mainWebView.setVisibility(View.VISIBLE);
305 // Show the ad if this is the free flavor.
306 BannerAd.showAd(adView);
308 // Hide the fullScreenVideoFrameLayout.
309 assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
310 fullScreenVideoFrameLayout.removeAllViews();
311 fullScreenVideoFrameLayout.setVisibility(View.GONE);
315 // Allow the downloading of files.
316 mainWebView.setDownloadListener(new DownloadListener() {
317 // Launch the Android download manager when a link leads to a download.
319 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
320 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
321 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
323 // Add the URL as the description for the download.
324 requestUri.setDescription(url);
326 // Show the download notification after the download is completed.
327 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
329 // Initiate the download and display a Snackbar.
330 downloadManager.enqueue(requestUri);
331 Snackbar.make(findViewById(R.id.mainWebView), R.string.download_started, Snackbar.LENGTH_SHORT).show();
335 // Allow pinch to zoom.
336 mainWebView.getSettings().setBuiltInZoomControls(true);
338 // Hide zoom controls.
339 mainWebView.getSettings().setDisplayZoomControls(false);
342 // Initialize the default preference values the first time the program is run.
343 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
345 // Get the shared preference values.
346 SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
348 // Set JavaScript initial status. The default value is false.
349 javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
350 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
352 // Initialize cookieManager.
353 cookieManager = CookieManager.getInstance();
355 // Set cookies initial status. The default value is false.
356 firstPartyCookiesEnabled = savedPreferences.getBoolean("first_party_cookies_enabled", false);
357 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
359 // Set third-party cookies initial status if API >= 21. The default value is false.
360 if (Build.VERSION.SDK_INT >= 21) {
361 thirdPartyCookiesEnabled = savedPreferences.getBoolean("third_party_cookies_enabled", false);
362 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
365 // Set DOM storage initial status. The default value is false.
366 domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
367 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
369 // Set the saved form data initial status. The default is false.
370 saveFormDataEnabled = savedPreferences.getBoolean("save_form_data_enabled", false);
371 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
373 // Set the user agent initial status.
374 String userAgentString = savedPreferences.getString("user_agent", "Default user agent");
375 switch (userAgentString) {
376 case "Default user agent":
380 case "Custom user agent":
381 // Set the custom user agent on mainWebView, The default is "PrivacyBrowser/1.0".
382 mainWebView.getSettings().setUserAgentString(savedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0"));
386 // Set the selected user agent on mainWebView. The default is "PrivacyBrowser/1.0".
387 mainWebView.getSettings().setUserAgentString(savedPreferences.getString("user_agent", "PrivacyBrowser/1.0"));
391 // Set the initial string for JavaScript disabled search.
392 if (savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=").equals("Custom URL")) {
393 // Get the custom URL string. The default is "".
394 javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search_custom_url", "");
396 // Use the string from javascript_disabled_search.
397 javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
400 // Set the initial string for JavaScript enabled search.
401 if (savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=").equals("Custom URL")) {
402 // Get the custom URL string. The default is "".
403 javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search_custom_url", "");
405 // Use the string from javascript_enabled_search.
406 javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
410 // Set homepage initial status. The default value is "https://www.duckduckgo.com".
411 homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
413 // Set swipe to refresh initial status. The default is true.
414 swipeToRefreshEnabled = savedPreferences.getBoolean("swipe_to_refresh_enabled", true);
415 swipeToRefresh.setEnabled(swipeToRefreshEnabled);
418 // Get the intent information that started the app.
419 final Intent intent = getIntent();
421 if (intent.getData() != null) {
422 // Get the intent data and convert it to a string.
423 final Uri intentUriData = intent.getData();
424 formattedUrlString = intentUriData.toString();
427 // If formattedUrlString is null assign the homepage to it.
428 if (formattedUrlString == null) {
429 formattedUrlString = homepage;
432 // Load the initial website.
433 mainWebView.loadUrl(formattedUrlString);
435 // Load the default favorite icon if it is null.
436 if (favoriteIcon == null) {
437 // We have to use `ContextCompat` until API >= 21.
438 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
439 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
440 favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
443 // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing.
444 adView = findViewById(R.id.adView);
445 BannerAd.requestAd(adView);
450 protected void onNewIntent(Intent intent) {
451 // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
454 if (intent.getData() != null) {
455 // Get the intent data and convert it to a string.
456 final Uri intentUriData = intent.getData();
457 formattedUrlString = intentUriData.toString();
460 // Close the navigation drawer if it is open.
461 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
462 drawerLayout.closeDrawer(GravityCompat.START);
466 mainWebView.loadUrl(formattedUrlString);
468 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
469 mainWebView.requestFocus();
473 public boolean onCreateOptionsMenu(Menu menu) {
474 // Inflate the menu; this adds items to the action bar if it is present.
475 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
477 // Set mainMenu so it can be used by onOptionsItemSelected.
480 // Initialize privacyIcon
481 privacyIcon = menu.findItem(R.id.toggleJavaScript);
483 // Get MenuItems for checkable menu items.
484 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
485 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
486 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
487 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
489 // Set the initial status of the privacy icon.
492 // Set the initial status of the menu item checkboxes.
493 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
494 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
495 toggleDomStorage.setChecked(domStorageEnabled);
496 toggleSaveFormData.setChecked(saveFormDataEnabled);
502 public boolean onPrepareOptionsMenu(Menu menu) {
503 // Only enable Third-Party Cookies if SDK >= 21 and First-Party Cookies are enabled.
504 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
505 if ((Build.VERSION.SDK_INT >= 21) && firstPartyCookiesEnabled) {
506 toggleThirdPartyCookies.setEnabled(true);
508 toggleThirdPartyCookies.setEnabled(false);
511 // Enable DOM Storage if JavaScript is enabled.
512 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
513 toggleDomStorage.setEnabled(javaScriptEnabled);
515 // Enable Clear Cookies if there are any.
516 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
517 clearCookies.setEnabled(cookieManager.hasCookies());
519 // Enable Clear Form Data is there is any.
520 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
521 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
522 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
524 // Run all the other default commands.
525 super.onPrepareOptionsMenu(menu);
527 // `return true` displays the menu.
532 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
533 @SuppressLint("SetJavaScriptEnabled")
534 // removeAllCookies is deprecated, but it is required for API < 21.
535 @SuppressWarnings("deprecation")
536 public boolean onOptionsItemSelected(MenuItem menuItem) {
537 int menuItemId = menuItem.getItemId();
539 // Set the commands that relate to the menu entries.
540 switch (menuItemId) {
541 case R.id.toggleJavaScript:
542 // Switch the status of javaScriptEnabled.
543 javaScriptEnabled = !javaScriptEnabled;
545 // Apply the new JavaScript status.
546 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
548 // Update the privacy icon.
551 // Display a Snackbar.
552 if (javaScriptEnabled) {
553 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
555 if (firstPartyCookiesEnabled) {
556 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
558 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
562 // Reload the WebView.
563 mainWebView.reload();
566 case R.id.toggleFirstPartyCookies:
567 // Switch the status of firstPartyCookiesEnabled.
568 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
570 // Update the menu checkbox.
571 menuItem.setChecked(firstPartyCookiesEnabled);
573 // Apply the new cookie status.
574 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
576 // Update the privacy icon.
579 // Reload the WebView.
580 mainWebView.reload();
583 case R.id.toggleThirdPartyCookies:
584 if (Build.VERSION.SDK_INT >= 21) {
585 // Switch the status of thirdPartyCookiesEnabled.
586 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
588 // Update the menu checkbox.
589 menuItem.setChecked(thirdPartyCookiesEnabled);
591 // Apply the new cookie status.
592 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
594 // Reload the WebView.
595 mainWebView.reload();
596 } // Else do nothing because SDK < 21.
599 case R.id.toggleDomStorage:
600 // Switch the status of domStorageEnabled.
601 domStorageEnabled = !domStorageEnabled;
603 // Update the menu checkbox.
604 menuItem.setChecked(domStorageEnabled);
606 // Apply the new DOM Storage status.
607 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
609 // Reload the WebView.
610 mainWebView.reload();
613 case R.id.toggleSaveFormData:
614 // Switch the status of saveFormDataEnabled.
615 saveFormDataEnabled = !saveFormDataEnabled;
617 // Update the menu checkbox.
618 menuItem.setChecked(saveFormDataEnabled);
620 // Apply the new form data status.
621 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
623 // Reload the WebView.
624 mainWebView.reload();
627 case R.id.clearCookies:
628 if (Build.VERSION.SDK_INT < 21) {
629 cookieManager.removeAllCookie();
631 cookieManager.removeAllCookies(null);
633 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
636 case R.id.clearDomStorage:
637 WebStorage webStorage = WebStorage.getInstance();
638 webStorage.deleteAllData();
639 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
642 case R.id.clearFormData:
643 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
644 mainWebViewDatabase.clearFormData();
645 mainWebView.reload();
649 Intent shareIntent = new Intent();
650 shareIntent.setAction(Intent.ACTION_SEND);
651 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
652 shareIntent.setType("text/plain");
653 startActivity(Intent.createChooser(shareIntent, "Share URL"));
656 case R.id.addToHomescreen:
657 // Show the CreateHomeScreenShortcut AlertDialog and name this instance "@string/create_shortcut".
658 DialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
659 createHomeScreenShortcutDialogFragment.show(getFragmentManager(), getResources().getString(R.string.create_shortcut));
661 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
665 mainWebView.reload();
669 // Don't consume the event.
670 return super.onOptionsItemSelected(menuItem);
675 // removeAllCookies is deprecated, but it is required for API < 21.
676 @SuppressWarnings("deprecation")
677 public boolean onNavigationItemSelected(MenuItem menuItem) {
678 int menuItemId = menuItem.getItemId();
680 switch (menuItemId) {
682 mainWebView.loadUrl(homepage);
686 if (mainWebView.canGoBack()) {
687 mainWebView.goBack();
692 if (mainWebView.canGoForward()) {
693 mainWebView.goForward();
698 // Launch BookmarksActivity.
699 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
700 startActivity(bookmarksIntent);
704 // Launch the system Download Manager.
705 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
707 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
708 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
710 startActivity(downloadManagerIntent);
714 // Launch `SettingsActivity`.
715 Intent settingsIntent = new Intent(this, SettingsActivity.class);
716 startActivity(settingsIntent);
720 // Launch `GuideActivity`.
721 Intent guideIntent = new Intent(this, GuideActivity.class);
722 startActivity(guideIntent);
726 // Launch `AboutActivity`.
727 Intent aboutIntent = new Intent(this, AboutActivity.class);
728 startActivity(aboutIntent);
731 case R.id.clearAndExit:
732 // Clear cookies. The commands changed slightly in API 21.
733 if (Build.VERSION.SDK_INT >= 21) {
734 cookieManager.removeAllCookies(null);
736 cookieManager.removeAllCookie();
739 // Clear DOM storage.
740 WebStorage domStorage = WebStorage.getInstance();
741 domStorage.deleteAllData();
744 WebViewDatabase formData = WebViewDatabase.getInstance(this);
745 formData.clearFormData();
747 // Clear cache. The argument of "true" includes disk files.
748 mainWebView.clearCache(true);
750 // Clear the back/forward history.
751 mainWebView.clearHistory();
753 formattedUrlString = null;
755 // Destroy the internal state of the webview.
756 mainWebView.destroy();
758 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
759 if (Build.VERSION.SDK_INT >= 21) {
760 finishAndRemoveTask();
770 // Close the navigation drawer.
771 drawerLayout.closeDrawer(GravityCompat.START);
776 public void onPostCreate(Bundle savedInstanceState) {
777 super.onPostCreate(savedInstanceState);
779 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
780 drawerToggle.syncState();
784 public void onConfigurationChanged(Configuration newConfig) {
785 super.onConfigurationChanged(newConfig);
787 // Reload the ad if this is the free flavor.
788 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
790 // Reinitialize the adView variable, as the View will have been removed and re-added in the free flavor by BannerAd.reloadAfterRotate().
791 adView = findViewById(R.id.adView);
795 public void onCancelCreateHomeScreenShortcut(DialogFragment dialogFragment) {
796 // Do nothing because the user selected "Cancel".
800 public void onCreateHomeScreenShortcut(DialogFragment dialogFragment) {
801 // Get shortcutNameEditText from the alert dialog.
802 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
804 // Create the bookmark shortcut based on formattedUrlString.
805 Intent bookmarkShortcut = new Intent();
806 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
807 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
809 // Place the bookmark shortcut on the home screen.
810 Intent placeBookmarkShortcut = new Intent();
811 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
812 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
813 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
814 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
815 sendBroadcast(placeBookmarkShortcut);
818 // Override onBackPressed to handle the navigation drawer and mainWebView.
820 public void onBackPressed() {
821 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
823 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
824 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
825 drawerLayout.closeDrawer(GravityCompat.START);
827 // Load the previous URL if available.
828 assert mainWebView != null; //This assert removes the incorrect warning in Android Studio on the following line that mainWebView might be null.
829 if (mainWebView.canGoBack()) {
830 mainWebView.goBack();
832 // Pass onBackPressed to the system.
833 super.onBackPressed();
839 public void onPause() {
840 // We need to pause the adView or it will continue to consume resources in the background on the free flavor.
841 BannerAd.pauseAd(adView);
847 public void onResume() {
850 // We need to resume the adView for the free flavor.
851 BannerAd.resumeAd(adView);
854 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
855 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
856 String unformattedUrlString = urlTextBox.getText().toString().trim();
858 URL unformattedUrl = null;
859 Uri.Builder formattedUri = new Uri.Builder();
861 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
862 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
863 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
864 if (!unformattedUrlString.startsWith("http")) {
865 unformattedUrlString = "http://" + unformattedUrlString;
868 // 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.
870 unformattedUrl = new URL(unformattedUrlString);
871 } catch (MalformedURLException e) {
875 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
876 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
877 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
878 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
879 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
880 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
882 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
883 formattedUrlString = formattedUri.build().toString();
885 // Sanitize the search input and convert it to a DuckDuckGo search.
886 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
888 // Use the correct search URL based on javaScriptEnabled.
889 if (javaScriptEnabled) {
890 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
891 } else { // JavaScript is disabled.
892 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
896 mainWebView.loadUrl(formattedUrlString);
898 // Hides the keyboard so we can see the webpage.
899 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
900 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
903 private void updatePrivacyIcon() {
904 if (javaScriptEnabled) {
905 privacyIcon.setIcon(R.drawable.javascript_enabled);
907 if (firstPartyCookiesEnabled) {
908 privacyIcon.setIcon(R.drawable.warning);
910 privacyIcon.setIcon(R.drawable.privacy_mode);