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.webkit.WebViewDatabase;
57 import android.widget.EditText;
58 import android.widget.FrameLayout;
59 import android.widget.ImageView;
60 import android.widget.ProgressBar;
62 import java.io.UnsupportedEncodingException;
63 import java.net.MalformedURLException;
65 import java.net.URLEncoder;
67 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
68 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener {
69 // favoriteIcon is public static so it can be accessed from CreateHomeScreenShortcut.
70 public static Bitmap favoriteIcon;
71 // mainWebView is public static so it can be accessed from SettingsFragment. It is also used in onCreate(), onOptionsItemSelected(), onNavigationItemSelected(), and loadUrlFromTextBox().
72 public static WebView mainWebView;
74 // mainMenu is public static so it can be accessed from SettingsFragment. It is also used in onCreateOptionsMenu() and onOptionsItemSelected().
75 public static Menu mainMenu;
76 // cookieManager is public static so it can be accessed from SettingsFragment. It is also used in onCreate(), onOptionsItemSelected(), and onNavigationItemSelected().
77 public static CookieManager cookieManager;
78 // javaScriptEnabled is public static so it can be accessed from SettingsFragment. It is also used in onCreate(), onCreateOptionsMenu(), onOptionsItemSelected(), and loadUrlFromTextBox().
79 public static boolean javaScriptEnabled;
80 // firstPartyCookiesEnabled is public static so it can be accessed from SettingsFragment. It is also used in onCreate(), onCreateOptionsMenu(), onPrepareOptionsMenu(), and onOptionsItemSelected().
81 public static boolean firstPartyCookiesEnabled;
82 // thirdPartyCookiesEnabled is used in onCreate(), onCreateOptionsMenu(), onPrepareOptionsMenu(), and onOptionsItemSelected().
83 public static boolean thirdPartyCookiesEnabled;
84 // domStorageEnabled is public static so it can be accessed from SettingsFragment. It is also used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
85 public static boolean domStorageEnabled;
86 // saveFormDataEnabled is public static so it can be accessed from SettingsFragment. It is also used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
87 public static boolean saveFormDataEnabled;
88 // javaScriptDisabledSearchURL is public static so it can be accessed from SettingsFragment. It is also used in onCreate() and loadURLFromTextBox().
89 public static String javaScriptDisabledSearchURL;
90 // javaScriptEnabledSearchURL is public static so it can be accessed from SettingsFragment. It is also used in onCreate() and loadURLFromTextBox().
91 public static String javaScriptEnabledSearchURL;
92 // homepage is public static so it can be accessed from SettingsFragment. It is also used in onCreate() and onOptionsItemSelected().
93 public static String homepage;
94 // swipeToRefresh is public static so it can be accessed from SettingsFragment. It is also used in onCreate().
95 public static SwipeRefreshLayout swipeToRefresh;
96 // swipeToRefreshEnabled is public static so it can be accessed from SettingsFragment. It is also used in onCreate().
97 public static boolean swipeToRefreshEnabled;
99 // drawerToggle is used in onCreate(), onPostCreate(), onConfigurationChanged(), onNewIntent(), and onNavigationItemSelected().
100 private ActionBarDrawerToggle drawerToggle;
101 // drawerLayout is used in onCreate(), onNewIntent(), and onBackPressed().
102 private DrawerLayout drawerLayout;
103 // formattedUrlString is used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
104 private String formattedUrlString;
105 // privacyIcon is used in onCreateOptionsMenu() and updatePrivacyIcon().
106 private MenuItem privacyIcon;
107 // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
108 private EditText urlTextBox;
109 // adView is used in onCreate() and onConfigurationChanged().
113 // 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.
114 @SuppressLint("SetJavaScriptEnabled")
115 protected void onCreate(Bundle savedInstanceState) {
116 super.onCreate(savedInstanceState);
117 setContentView(R.layout.main_coordinatorlayout);
119 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
120 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
121 setSupportActionBar(supportAppBar);
122 final ActionBar appBar = getSupportActionBar();
124 // This is needed to get rid of the Android Studio warning that appBar might be null.
125 assert appBar != null;
127 // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
128 appBar.setCustomView(R.layout.url_bar);
129 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
131 // Set the "go" button on the keyboard to load the URL in urlTextBox.
132 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
133 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
134 public boolean onKey(View v, int keyCode, KeyEvent event) {
135 // If the event is a key-down event on the "enter" button, load the URL.
136 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
137 // Load the URL into the mainWebView and consume the event.
139 loadUrlFromTextBox();
140 } catch (UnsupportedEncodingException e) {
143 // If the enter key was pressed, consume the event.
146 // If any other key was pressed, do not consume the event.
152 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
154 // Implement swipe to refresh
155 swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
156 assert swipeToRefresh != null; //This assert removes the incorrect warning on the following line that swipeToRefresh might be null.
157 swipeToRefresh.setColorSchemeResources(R.color.blue);
158 swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
160 public void onRefresh() {
161 mainWebView.reload();
165 mainWebView = (WebView) findViewById(R.id.mainWebView);
167 // Create the navigation drawer.
168 drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
169 // The DrawerTitle identifies the drawer in accessibility mode.
170 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
172 // Listen for touches on the navigation menu.
173 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
174 assert navigationView != null; // This assert removes the incorrect warning on the following line that navigationView might be null.
175 navigationView.setNavigationItemSelectedListener(this);
177 // drawerToggle creates the hamburger icon at the start of the AppBar.
178 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
180 mainWebView.setWebViewClient(new WebViewClient() {
181 // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
183 public boolean shouldOverrideUrlLoading(WebView view, String url) {
184 mainWebView.loadUrl(url);
188 // Update the URL in urlTextBox when the page starts to load.
190 public void onPageStarted(WebView view, String url, Bitmap favicon) {
191 urlTextBox.setText(url);
194 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
196 public void onPageFinished(WebView view, String url) {
197 formattedUrlString = url;
199 // Only update urlTextBox if the user is not typing in it.
200 if (!urlTextBox.hasFocus()) {
201 urlTextBox.setText(formattedUrlString);
206 mainWebView.setWebChromeClient(new WebChromeClient() {
207 // Update the progress bar when a page is loading.
209 public void onProgressChanged(WebView view, int progress) {
210 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
211 progressBar.setProgress(progress);
212 if (progress < 100) {
213 progressBar.setVisibility(View.VISIBLE);
215 progressBar.setVisibility(View.GONE);
217 //Stop the SwipeToRefresh indicator if it is running
218 swipeToRefresh.setRefreshing(false);
222 // Set the favorite icon when it changes.
224 public void onReceivedIcon(WebView view, Bitmap icon) {
225 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
228 // Place the favorite icon in the appBar.
229 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
230 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
233 // Enter full screen video
235 public void onShowCustomView(View view, CustomViewCallback callback) {
238 // Show the fullScreenVideoFrameLayout.
239 assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
240 fullScreenVideoFrameLayout.addView(view);
241 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
243 // Hide the mainWebView.
244 mainWebView.setVisibility(View.GONE);
246 // Hide the ad if this is the free flavor.
247 BannerAd.hideAd(adView);
249 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
250 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
251 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
253 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
256 // Exit full screen video
257 public void onHideCustomView() {
260 // Show the mainWebView.
261 mainWebView.setVisibility(View.VISIBLE);
263 // Show the ad if this is the free flavor.
264 BannerAd.showAd(adView);
266 // Hide the fullScreenVideoFrameLayout.
267 assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
268 fullScreenVideoFrameLayout.removeAllViews();
269 fullScreenVideoFrameLayout.setVisibility(View.GONE);
273 // Allow the downloading of files.
274 mainWebView.setDownloadListener(new DownloadListener() {
275 // Launch the Android download manager when a link leads to a download.
277 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
278 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
279 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
281 // Add the URL as the description for the download.
282 requestUri.setDescription(url);
284 // Show the download notification after the download is completed.
285 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
287 // Initiate the download and display a Snackbar.
288 downloadManager.enqueue(requestUri);
289 Snackbar.make(findViewById(R.id.mainWebView), R.string.download_started, Snackbar.LENGTH_SHORT).show();
293 // Allow pinch to zoom.
294 mainWebView.getSettings().setBuiltInZoomControls(true);
296 // Hide zoom controls.
297 mainWebView.getSettings().setDisplayZoomControls(false);
300 // Initialize the default preference values the first time the program is run.
301 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
303 // Get the shared preference values.
304 SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
306 // Set JavaScript initial status. The default value is false.
307 javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
308 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
310 // Initialize cookieManager.
311 cookieManager = CookieManager.getInstance();
313 // Set cookies initial status. The default value is false.
314 firstPartyCookiesEnabled = savedPreferences.getBoolean("first_party_cookies_enabled", false);
315 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
317 // Set third-party cookies initial status if API >= 21. The default value is false.
318 if (Build.VERSION.SDK_INT >= 21) {
319 thirdPartyCookiesEnabled = savedPreferences.getBoolean("third_party_cookies_enabled", false);
320 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
323 // Set DOM storage initial status. The default value is false.
324 domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
325 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
327 // Set the saved form data initial status. The default is false.
328 saveFormDataEnabled = savedPreferences.getBoolean("save_form_data_enabled", false);
329 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
331 // Set the user agent initial status.
332 String userAgentString = savedPreferences.getString("user_agent", "Default user agent");
333 switch (userAgentString) {
334 case "Default user agent":
338 case "Custom user agent":
339 // Set the custom user agent on mainWebView, The default is "PrivacyBrowser/1.0".
340 mainWebView.getSettings().setUserAgentString(savedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0"));
344 // Set the selected user agent on mainWebView. The default is "PrivacyBrowser/1.0".
345 mainWebView.getSettings().setUserAgentString(savedPreferences.getString("user_agent", "PrivacyBrowser/1.0"));
349 // Set the initial string for JavaScript disabled search.
350 if (savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=").equals("Custom URL")) {
351 // Get the custom URL string. The default is "".
352 javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search_custom_url", "");
354 // Use the string from javascript_disabled_search.
355 javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
358 // Set the initial string for JavaScript enabled search.
359 if (savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=").equals("Custom URL")) {
360 // Get the custom URL string. The default is "".
361 javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search_custom_url", "");
363 // Use the string from javascript_enabled_search.
364 javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
368 // Set homepage initial status. The default value is "https://www.duckduckgo.com".
369 homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
371 // Set swipe to refresh initial status. The default is true.
372 swipeToRefreshEnabled = savedPreferences.getBoolean("swipe_to_refresh_enabled", true);
373 swipeToRefresh.setEnabled(swipeToRefreshEnabled);
376 // Get the intent information that started the app.
377 final Intent intent = getIntent();
379 if (intent.getData() != null) {
380 // Get the intent data and convert it to a string.
381 final Uri intentUriData = intent.getData();
382 formattedUrlString = intentUriData.toString();
385 // If formattedUrlString is null assign the homepage to it.
386 if (formattedUrlString == null) {
387 formattedUrlString = homepage;
390 // Load the initial website.
391 mainWebView.loadUrl(formattedUrlString);
393 // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing.
394 adView = findViewById(R.id.adView);
395 BannerAd.requestAd(adView);
400 protected void onNewIntent(Intent intent) {
401 // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
404 if (intent.getData() != null) {
405 // Get the intent data and convert it to a string.
406 final Uri intentUriData = intent.getData();
407 formattedUrlString = intentUriData.toString();
410 // Close the navigation drawer if it is open.
411 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
412 drawerLayout.closeDrawer(GravityCompat.START);
416 mainWebView.loadUrl(formattedUrlString);
418 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
419 mainWebView.requestFocus();
423 public boolean onCreateOptionsMenu(Menu menu) {
424 // Inflate the menu; this adds items to the action bar if it is present.
425 getMenuInflater().inflate(R.menu.menu_options, menu);
427 // Set mainMenu so it can be used by onOptionsItemSelected.
430 // Initialize privacyIcon
431 privacyIcon = menu.findItem(R.id.toggleJavaScript);
433 // Get MenuItems for checkable menu items.
434 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
435 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
436 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
437 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
439 // Set the initial status of the privacy icon.
442 // Set the initial status of the menu item checkboxes.
443 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
444 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
445 toggleDomStorage.setChecked(domStorageEnabled);
446 toggleSaveFormData.setChecked(saveFormDataEnabled);
452 public boolean onPrepareOptionsMenu(Menu menu) {
453 // Only enable Third-Party Cookies if SDK >= 21 and First-Party Cookies are enabled.
454 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
455 if ((Build.VERSION.SDK_INT >= 21) && firstPartyCookiesEnabled) {
456 toggleThirdPartyCookies.setEnabled(true);
458 toggleThirdPartyCookies.setEnabled(false);
461 // Enable DOM Storage if JavaScript is enabled.
462 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
463 toggleDomStorage.setEnabled(javaScriptEnabled);
465 // Enable Clear Cookies if there are any.
466 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
467 clearCookies.setEnabled(cookieManager.hasCookies());
469 // Enable Clear Form Data is there is any.
470 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
471 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
472 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
474 // Run all the other default commands.
475 super.onPrepareOptionsMenu(menu);
477 // return true displays the menu.
482 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
483 @SuppressLint("SetJavaScriptEnabled")
484 // removeAllCookies is deprecated, but it is required for API < 21.
485 @SuppressWarnings("deprecation")
486 public boolean onOptionsItemSelected(MenuItem menuItem) {
487 int menuItemId = menuItem.getItemId();
489 // Set the commands that relate to the menu entries.
490 switch (menuItemId) {
491 case R.id.toggleJavaScript:
492 // Switch the status of javaScriptEnabled.
493 javaScriptEnabled = !javaScriptEnabled;
495 // Apply the new JavaScript status.
496 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
498 // Update the privacy icon.
501 // Display a Snackbar.
502 if (javaScriptEnabled) {
503 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
505 if (firstPartyCookiesEnabled) {
506 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
508 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
512 // Reload the WebView.
513 mainWebView.reload();
516 case R.id.toggleFirstPartyCookies:
517 // Switch the status of firstPartyCookiesEnabled.
518 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
520 // Update the menu checkbox.
521 menuItem.setChecked(firstPartyCookiesEnabled);
523 // Apply the new cookie status.
524 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
526 // Update the privacy icon.
529 // Reload the WebView.
530 mainWebView.reload();
533 case R.id.toggleThirdPartyCookies:
534 if (Build.VERSION.SDK_INT >= 21) {
535 // Switch the status of thirdPartyCookiesEnabled.
536 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
538 // Update the menu checkbox.
539 menuItem.setChecked(thirdPartyCookiesEnabled);
541 // Apply the new cookie status.
542 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
544 // Reload the WebView.
545 mainWebView.reload();
546 } // Else do nothing because SDK < 21.
549 case R.id.toggleDomStorage:
550 // Switch the status of domStorageEnabled.
551 domStorageEnabled = !domStorageEnabled;
553 // Update the menu checkbox.
554 menuItem.setChecked(domStorageEnabled);
556 // Apply the new DOM Storage status.
557 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
559 // Reload the WebView.
560 mainWebView.reload();
563 case R.id.toggleSaveFormData:
564 // Switch the status of saveFormDataEnabled.
565 saveFormDataEnabled = !saveFormDataEnabled;
567 // Update the menu checkbox.
568 menuItem.setChecked(saveFormDataEnabled);
570 // Apply the new form data status.
571 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
573 // Reload the WebView.
574 mainWebView.reload();
577 case R.id.clearCookies:
578 if (Build.VERSION.SDK_INT < 21) {
579 cookieManager.removeAllCookie();
581 cookieManager.removeAllCookies(null);
583 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
586 case R.id.clearDomStorage:
587 WebStorage webStorage = WebStorage.getInstance();
588 webStorage.deleteAllData();
589 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
592 case R.id.clearFormData:
593 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
594 mainWebViewDatabase.clearFormData();
595 mainWebView.reload();
599 Intent shareIntent = new Intent();
600 shareIntent.setAction(Intent.ACTION_SEND);
601 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
602 shareIntent.setType("text/plain");
603 startActivity(Intent.createChooser(shareIntent, "Share URL"));
606 case R.id.addToHomescreen:
607 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
608 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
609 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
611 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
615 mainWebView.reload();
619 // Don't consume the event.
620 return super.onOptionsItemSelected(menuItem);
625 // removeAllCookies is deprecated, but it is required for API < 21.
626 @SuppressWarnings("deprecation")
627 public boolean onNavigationItemSelected(MenuItem menuItem) {
628 int menuItemId = menuItem.getItemId();
630 switch (menuItemId) {
632 mainWebView.loadUrl(homepage);
636 if (mainWebView.canGoBack()) {
637 mainWebView.goBack();
642 if (mainWebView.canGoForward()) {
643 mainWebView.goForward();
648 // Launch the system Download Manager.
649 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
651 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
652 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
654 startActivity(downloadManagerIntent);
658 // Launch GuideActivity.
659 Intent guideIntent = new Intent(this, GuideActivity.class);
660 startActivity(guideIntent);
664 // Launch SettingsActivity.
665 Intent settingsIntent = new Intent(this, SettingsActivity.class);
666 startActivity(settingsIntent);
670 // Launch AboutActivity.
671 Intent aboutIntent = new Intent(this, AboutActivity.class);
672 startActivity(aboutIntent);
675 case R.id.clearAndExit:
676 // Clear cookies. The commands changed slightly in API 21.
677 if (Build.VERSION.SDK_INT >= 21) {
678 cookieManager.removeAllCookies(null);
680 cookieManager.removeAllCookie();
683 // Clear DOM storage.
684 WebStorage domStorage = WebStorage.getInstance();
685 domStorage.deleteAllData();
687 // Clear cache. The argument of "true" includes disk files.
688 mainWebView.clearCache(true);
690 // Clear the back/forward history.
691 mainWebView.clearHistory();
693 // Destroy the internal state of the webview.
694 mainWebView.destroy();
696 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
697 if (Build.VERSION.SDK_INT >= 21) {
698 finishAndRemoveTask();
708 // Close the navigation drawer.
709 drawerLayout.closeDrawer(GravityCompat.START);
714 public void onPostCreate(Bundle savedInstanceState) {
715 super.onPostCreate(savedInstanceState);
717 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
718 drawerToggle.syncState();
722 public void onConfigurationChanged(Configuration newConfig) {
723 super.onConfigurationChanged(newConfig);
725 // Reload the ad if this is the free flavor.
726 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
728 // Reinitialize the adView variable, as the View will have been removed and re-added in the free flavor by BannerAd.reloadAfterRotate().
729 adView = findViewById(R.id.adView);
733 public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
734 // Do nothing because the user selected "Cancel".
738 public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
739 // Get shortcutNameEditText from the alert dialog.
740 EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
742 // Create the bookmark shortcut based on formattedUrlString.
743 Intent bookmarkShortcut = new Intent();
744 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
745 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
747 // Place the bookmark shortcut on the home screen.
748 Intent placeBookmarkShortcut = new Intent();
749 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
750 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
751 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
752 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
753 sendBroadcast(placeBookmarkShortcut);
756 // Override onBackPressed to handle the navigation drawer and mainWebView.
758 public void onBackPressed() {
759 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
761 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
762 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
763 drawerLayout.closeDrawer(GravityCompat.START);
765 // Load the previous URL if available.
766 assert mainWebView != null; //This assert removes the incorrect warning in Android Studio on the following line that mainWebView might be null.
767 if (mainWebView.canGoBack()) {
768 mainWebView.goBack();
770 // Pass onBackPressed to the system.
771 super.onBackPressed();
777 public void onPause() {
778 // We need to pause the adView or it will continue to consume resources in the background on the free flavor.
779 BannerAd.pauseAd(adView);
785 public void onResume() {
788 // We need to resume the adView for the free flavor.
789 BannerAd.resumeAd(adView);
792 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
793 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
794 String unformattedUrlString = urlTextBox.getText().toString().trim();
796 URL unformattedUrl = null;
797 Uri.Builder formattedUri = new Uri.Builder();
799 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
800 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
801 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
802 if (!unformattedUrlString.startsWith("http")) {
803 unformattedUrlString = "http://" + unformattedUrlString;
806 // 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.
808 unformattedUrl = new URL(unformattedUrlString);
809 } catch (MalformedURLException e) {
813 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
814 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
815 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
816 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
817 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
818 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
820 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
821 formattedUrlString = formattedUri.build().toString();
823 // Sanitize the search input and convert it to a DuckDuckGo search.
824 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
826 // Use the correct search URL based on javaScriptEnabled.
827 if (javaScriptEnabled) {
828 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
829 } else { // JavaScript is disabled.
830 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
834 mainWebView.loadUrl(formattedUrlString);
836 // Hides the keyboard so we can see the webpage.
837 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
838 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
841 private void updatePrivacyIcon() {
842 if (javaScriptEnabled) {
843 privacyIcon.setIcon(R.drawable.javascript_enabled);
845 if (firstPartyCookiesEnabled) {
846 privacyIcon.setIcon(R.drawable.warning);
848 privacyIcon.setIcon(R.drawable.privacy_mode);