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 // cookiesEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
96 private boolean cookiesEnabled;
98 // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
99 private EditText urlTextBox;
102 // 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.
103 @SuppressLint("SetJavaScriptEnabled")
104 protected void onCreate(Bundle savedInstanceState) {
105 super.onCreate(savedInstanceState);
106 setContentView(R.layout.coordinator_layout);
108 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
109 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
110 setSupportActionBar(supportAppBar);
112 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
114 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
115 final ActionBar appBar = getSupportActionBar();
117 // Setup AdView for the free flavor.
118 final View adView = findViewById(R.id.adView);
120 // Implement swipe to refresh
121 final SwipeRefreshLayout swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
122 swipeToRefresh.setColorSchemeResources(R.color.blue);
123 swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
125 public void onRefresh() {
126 mainWebView.reload();
130 mainWebView = (WebView) findViewById(R.id.mainWebView);
132 if (appBar != null) {
133 // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
134 appBar.setCustomView(R.layout.url_bar);
135 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
137 // Set the "go" button on the keyboard to load the URL in urlTextBox.
138 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
139 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
140 public boolean onKey(View v, int keyCode, KeyEvent event) {
141 // If the event is a key-down event on the "enter" button, load the URL.
142 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
143 // Load the URL into the mainWebView and consume the event.
145 loadUrlFromTextBox();
146 } catch (UnsupportedEncodingException e) {
149 // If the enter key was pressed, consume the event.
152 // If any other key was pressed, do not consume the event.
159 // Create the navigation drawer.
160 drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
161 // The DrawerTitle identifies the drawer in accessibility mode.
162 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
164 // Listen for touches on the navigation menu.
165 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
166 navigationView.setNavigationItemSelectedListener(this);
168 // drawerToggle creates the hamburger icon at the start of the AppBar.
169 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
171 mainWebView.setWebViewClient(new WebViewClient() {
172 // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
174 public boolean shouldOverrideUrlLoading(WebView view, String url) {
175 mainWebView.loadUrl(url);
179 // Update the URL in urlTextBox when the page starts to load.
181 public void onPageStarted(WebView view, String url, Bitmap favicon) {
182 urlTextBox.setText(url);
185 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
187 public void onPageFinished(WebView view, String url) {
188 formattedUrlString = url;
190 // Only update urlTextBox if the user is not typing in it.
191 if (!urlTextBox.hasFocus()) {
192 urlTextBox.setText(formattedUrlString);
197 mainWebView.setWebChromeClient(new WebChromeClient() {
198 // Update the progress bar when a page is loading.
200 public void onProgressChanged(WebView view, int progress) {
201 // Make sure that appBar is not null.
202 if (appBar != null) {
203 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
204 progressBar.setProgress(progress);
205 if (progress < 100) {
206 progressBar.setVisibility(View.VISIBLE);
208 progressBar.setVisibility(View.GONE);
210 //Stop the SwipeToRefresh indicator if it is running
211 swipeToRefresh.setRefreshing(false);
216 // Set the favorite icon when it changes.
218 public void onReceivedIcon(WebView view, Bitmap icon) {
219 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
222 // Place the favorite icon in the appBar if it is not null.
223 if (appBar != null) {
224 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
225 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
229 // Enter full screen video
231 public void onShowCustomView(View view, CustomViewCallback callback) {
232 if (appBar != null) {
236 // Show the fullScreenVideoFrameLayout.
237 fullScreenVideoFrameLayout.addView(view);
238 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
240 // Hide the mainWebView.
241 mainWebView.setVisibility(View.GONE);
243 // Hide the ad if this is the free flavor.
244 BannerAd.hideAd(adView);
246 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
247 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
248 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
251 // Set the one flag supported by API >= 14.
252 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
254 // Set the two flags that are supported by API >= 16.
255 if (Build.VERSION.SDK_INT >= 16) {
256 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
259 // Set all three flags that are supported by API >= 19.
260 if (Build.VERSION.SDK_INT >= 19) {
261 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
265 // Exit full screen video
266 public void onHideCustomView() {
267 if (appBar != null) {
271 // Show the mainWebView.
272 mainWebView.setVisibility(View.VISIBLE);
274 // Show the ad if this is the free flavor.
275 BannerAd.showAd(adView);
277 // Hide the fullScreenVideoFrameLayout.
278 fullScreenVideoFrameLayout.removeAllViews();
279 fullScreenVideoFrameLayout.setVisibility(View.GONE);
283 // Allow the downloading of files.
284 mainWebView.setDownloadListener(new DownloadListener() {
285 // Launch the Android download manager when a link leads to a download.
287 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
288 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
289 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
291 // Add the URL as the description for the download.
292 requestUri.setDescription(url);
294 // Show the download notification after the download is completed.
295 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
297 // Initiate the download and display a Snackbar.
298 downloadManager.enqueue(requestUri);
299 Snackbar.make(findViewById(R.id.mainWebView), R.string.download_started, Snackbar.LENGTH_SHORT).show();
303 // Allow pinch to zoom.
304 mainWebView.getSettings().setBuiltInZoomControls(true);
306 // Hide zoom controls.
307 mainWebView.getSettings().setDisplayZoomControls(false);
309 // Initialize the default preference values the first time the program is run.
310 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
312 // Get the shared preference values.
313 SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
315 // Set JavaScript initial status.
316 javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
317 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
319 // Set DOM storage initial status.
320 domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
321 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
323 /* Save Form Data does nothing until database storage is implemented.
324 // Set Save Form Data initial status.
325 saveFormDataEnabled = true;
326 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
329 // Set cookies initial status.
330 cookiesEnabled = savedPreferences.getBoolean("cookies_enabled", false);
331 cookieManager = CookieManager.getInstance();
332 cookieManager.setAcceptCookie(cookiesEnabled);
334 // Set homepage initial status.
335 homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
337 // Get the intent information that started the app.
338 final Intent intent = getIntent();
340 if (intent.getData() != null) {
341 // Get the intent data and convert it to a string.
342 final Uri intentUriData = intent.getData();
343 formattedUrlString = intentUriData.toString();
346 // If formattedUrlString is null assign the homepage to it.
347 if (formattedUrlString == null) {
348 formattedUrlString = homepage;
351 // Load the initial website.
352 mainWebView.loadUrl(formattedUrlString);
354 // Load the ad if this is the free flavor.
355 BannerAd.requestAd(adView);
359 protected void onNewIntent(Intent intent) {
360 // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
363 if (intent.getData() != null) {
364 // Get the intent data and convert it to a string.
365 final Uri intentUriData = intent.getData();
366 formattedUrlString = intentUriData.toString();
369 // Close the navigation drawer if it is open.
370 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
371 drawerLayout.closeDrawer(GravityCompat.START);
375 mainWebView.loadUrl(formattedUrlString);
377 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
378 mainWebView.requestFocus();
382 public boolean onCreateOptionsMenu(Menu menu) {
383 // Inflate the menu; this adds items to the action bar if it is present.
384 getMenuInflater().inflate(R.menu.menu_options, menu);
386 // Set mainMenu so it can be used by onOptionsItemSelected.
389 // Get MenuItems for checkable menu items.
390 MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
391 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
392 /* toggleSaveFormData does nothing until database storage is implemented.
393 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
395 MenuItem toggleCookies = menu.findItem(R.id.toggleCookies);
397 // Set the initial icon for toggleJavaScript
398 if (javaScriptEnabled) {
399 toggleJavaScript.setIcon(R.drawable.javascript_enabled);
401 if (domStorageEnabled || cookiesEnabled) {
402 toggleJavaScript.setIcon(R.drawable.warning);
404 toggleJavaScript.setIcon(R.drawable.privacy_mode);
408 // Set the initial status of the menu item checkboxes.
409 toggleDomStorage.setChecked(domStorageEnabled);
410 /* toggleSaveFormData does nothing until database storage is implemented.
411 toggleSaveFormData.setChecked(saveFormDataEnabled);
413 toggleCookies.setChecked(cookiesEnabled);
419 public boolean onPrepareOptionsMenu(Menu menu) {
420 // Enable Clear Cookies if there are any.
421 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
422 clearCookies.setEnabled(cookieManager.hasCookies());
424 // Run all the other default commands.
425 super.onPrepareOptionsMenu(menu);
427 // return true displays the menu.
432 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
433 @SuppressLint("SetJavaScriptEnabled")
434 // removeAllCookies is deprecated, but it is required for API < 21.
435 @SuppressWarnings("deprecation")
436 public boolean onOptionsItemSelected(MenuItem menuItem) {
437 int menuItemId = menuItem.getItemId();
439 // Some options need to update the drawable for toggleJavaScript.
440 MenuItem toggleJavaScript = mainMenu.findItem(R.id.toggleJavaScript);
442 // Set the commands that relate to the menu entries.
443 switch (menuItemId) {
444 case R.id.toggleJavaScript:
445 if (javaScriptEnabled) {
446 javaScriptEnabled = false;
447 mainWebView.getSettings().setJavaScriptEnabled(false);
448 mainWebView.reload();
450 // Update the toggleJavaScript icon and display a snackbar.
451 if (domStorageEnabled || cookiesEnabled) {
452 menuItem.setIcon(R.drawable.warning);
453 if (domStorageEnabled && cookiesEnabled) {
454 Snackbar.make(findViewById(R.id.mainWebView), R.string.both_still_enabled, Snackbar.LENGTH_SHORT).show();
456 if (domStorageEnabled) {
457 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_still_enabled, Snackbar.LENGTH_SHORT).show();
459 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_still_enabled, Snackbar.LENGTH_SHORT).show();
463 menuItem.setIcon(R.drawable.privacy_mode);
464 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
467 javaScriptEnabled = true;
468 menuItem.setIcon(R.drawable.javascript_enabled);
469 mainWebView.getSettings().setJavaScriptEnabled(true);
470 mainWebView.reload();
471 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
475 case R.id.toggleDomStorage:
476 if (domStorageEnabled) {
477 domStorageEnabled = false;
478 menuItem.setChecked(false);
479 mainWebView.getSettings().setDomStorageEnabled(false);
480 mainWebView.reload();
482 // Update the toggleJavaScript icon and display a snackbar if appropriate.
483 if (!javaScriptEnabled && !cookiesEnabled) {
484 toggleJavaScript.setIcon(R.drawable.privacy_mode);
485 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
487 if (cookiesEnabled) {
488 toggleJavaScript.setIcon(R.drawable.warning);
489 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_still_enabled, Snackbar.LENGTH_SHORT).show();
490 } // Else Do nothing because JavaScript is enabled.
493 domStorageEnabled = true;
494 menuItem.setChecked(true);
495 mainWebView.getSettings().setDomStorageEnabled(true);
496 mainWebView.reload();
498 // Update the toggleJavaScript icon if appropriate.
499 if (!javaScriptEnabled) {
500 toggleJavaScript.setIcon(R.drawable.warning);
501 } // Else Do nothing because JavaScript is enabled.
503 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
507 /* toggleSaveFormData does nothing until database storage is implemented.
508 case R.id.toggleSaveFormData:
509 if (saveFormDataEnabled) {
510 saveFormDataEnabled = false;
511 menuItem.setChecked(false);
512 mainWebView.getSettings().setSaveFormData(false);
513 mainWebView.reload();
515 saveFormDataEnabled = true;
516 menuItem.setChecked(true);
517 mainWebView.getSettings().setSaveFormData(true);
518 mainWebView.reload();
523 case R.id.toggleCookies:
524 if (cookiesEnabled) {
525 cookiesEnabled = false;
526 menuItem.setChecked(false);
527 cookieManager.setAcceptCookie(false);
528 mainWebView.reload();
530 // Update the toggleJavaScript icon and display a snackbar if appropriate.
531 if (!javaScriptEnabled && !domStorageEnabled) {
532 toggleJavaScript.setIcon(R.drawable.privacy_mode);
533 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
535 if (domStorageEnabled) {
536 toggleJavaScript.setIcon(R.drawable.warning);
537 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
538 } // Else Do nothing because JavaScript is enabled.
541 cookiesEnabled = true;
542 menuItem.setChecked(true);
543 cookieManager.setAcceptCookie(true);
544 mainWebView.reload();
546 // Update the toggleJavaScript icon if appropriate.
547 if (!javaScriptEnabled) {
548 toggleJavaScript.setIcon(R.drawable.warning);
549 } // Else Do nothing because JavaScript is enabled.
551 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show();
555 case R.id.clearDomStorage:
556 WebStorage webStorage = WebStorage.getInstance();
557 webStorage.deleteAllData();
558 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
561 case R.id.clearCookies:
562 if (Build.VERSION.SDK_INT < 21) {
563 cookieManager.removeAllCookie();
565 cookieManager.removeAllCookies(null);
567 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
571 Intent shareIntent = new Intent();
572 shareIntent.setAction(Intent.ACTION_SEND);
573 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
574 shareIntent.setType("text/plain");
575 startActivity(Intent.createChooser(shareIntent, "Share URL"));
578 case R.id.addToHomescreen:
579 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
580 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
581 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
583 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
587 return super.onOptionsItemSelected(menuItem);
592 // removeAllCookies is deprecated, but it is required for API < 21.
593 @SuppressWarnings("deprecation")
594 public boolean onNavigationItemSelected(MenuItem menuItem) {
595 int menuItemId = menuItem.getItemId();
597 switch (menuItemId) {
599 mainWebView.loadUrl(homepage);
603 if (mainWebView.canGoBack()) {
604 mainWebView.goBack();
609 if (mainWebView.canGoForward()) {
610 mainWebView.goForward();
615 // Launch the system Download Manager.
616 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
618 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
619 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
621 startActivity(downloadManagerIntent);
625 // Launch SettingsActivity.
626 Intent intent = new Intent(this, SettingsActivity.class);
627 startActivity(intent);
631 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
632 AppCompatDialogFragment aboutDialog = new AboutDialog();
633 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
636 case R.id.clearAndExit:
637 // Clear DOM storage.
638 WebStorage domStorage = WebStorage.getInstance();
639 domStorage.deleteAllData();
641 // Clear cookies. The commands changed slightly in API 21.
642 if (Build.VERSION.SDK_INT >= 21) {
643 cookieManager.removeAllCookies(null);
645 cookieManager.removeAllCookie();
648 // Destroy the internal state of the webview.
649 mainWebView.destroy();
651 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
652 if (Build.VERSION.SDK_INT >= 21) {
653 finishAndRemoveTask();
663 // Close the navigation drawer.
664 drawerLayout.closeDrawer(GravityCompat.START);
669 public void onPostCreate(Bundle savedInstanceState) {
670 super.onPostCreate(savedInstanceState);
672 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
673 drawerToggle.syncState();
677 public void onConfigurationChanged(Configuration newConfig) {
678 super.onConfigurationChanged(newConfig);
680 // Update the status of the drawerToggle icon.
681 drawerToggle.onConfigurationChanged(newConfig);
685 public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
686 // Do nothing because the user selected "Cancel".
690 public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
691 // Get shortcutNameEditText from the alert dialog.
692 EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
694 // Create the bookmark shortcut based on formattedUrlString.
695 Intent bookmarkShortcut = new Intent();
696 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
697 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
699 // Place the bookmark shortcut on the home screen.
700 Intent placeBookmarkShortcut = new Intent();
701 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
702 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
703 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
704 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
705 sendBroadcast(placeBookmarkShortcut);
708 // Override onBackPressed to handle the navigation drawer and mainWebView.
710 public void onBackPressed() {
711 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
713 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
714 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
715 drawerLayout.closeDrawer(GravityCompat.START);
717 // Load the previous URL if available.
718 if (mainWebView.canGoBack()) {
719 mainWebView.goBack();
721 // Pass onBackPressed to the system.
722 super.onBackPressed();
727 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
728 // Get the text from urlTextBox and convert it to a string.
729 String unformattedUrlString = urlTextBox.getText().toString();
730 URL unformattedUrl = null;
731 Uri.Builder formattedUri = new Uri.Builder();
733 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
734 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
735 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
736 if (!unformattedUrlString.startsWith("http")) {
737 unformattedUrlString = "http://" + unformattedUrlString;
740 // 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.
742 unformattedUrl = new URL(unformattedUrlString);
743 } catch (MalformedURLException e) {
747 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
748 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
749 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
750 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
751 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
752 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
754 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
755 formattedUrlString = formattedUri.build().toString();
757 // Sanitize the search input and convert it to a DuckDuckGo search.
758 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
760 // Use the correct search URL based on javaScriptEnabled.
761 if (javaScriptEnabled) {
762 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
764 formattedUrlString = "https://duckduckgo.com/html/?q=" + encodedUrlString;
768 mainWebView.loadUrl(formattedUrlString);
770 // Hides the keyboard so we can see the webpage.
771 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
772 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);