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.annotation.TargetApi;
24 import android.app.Activity;
25 import android.app.DownloadManager;
26 import android.content.Intent;
27 import android.content.SharedPreferences;
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.Snackbar;
34 import android.support.v4.app.DialogFragment;
35 import android.support.v4.widget.SwipeRefreshLayout;
36 import android.support.v7.app.ActionBar;
37 import android.support.v7.app.AppCompatActivity;
38 import android.support.v7.app.AppCompatDialogFragment;
39 import android.support.v7.widget.Toolbar;
40 import android.util.Patterns;
41 import android.view.KeyEvent;
42 import android.view.Menu;
43 import android.view.MenuItem;
44 import android.view.View;
45 import android.view.inputmethod.InputMethodManager;
46 import android.webkit.CookieManager;
47 import android.webkit.DownloadListener;
48 import android.webkit.WebChromeClient;
49 import android.webkit.WebStorage;
50 import android.webkit.WebView;
51 import android.webkit.WebViewClient;
52 import android.widget.EditText;
53 import android.widget.FrameLayout;
54 import android.widget.ImageView;
55 import android.widget.ProgressBar;
56 import android.widget.Toast;
58 import java.io.UnsupportedEncodingException;
59 import java.net.MalformedURLException;
61 import java.net.URLEncoder;
63 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
64 public class MainWebViewActivity extends AppCompatActivity implements CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener {
65 // favoriteIcon is public static so it can be accessed from CreateHomeScreenShortcut.
66 public static Bitmap favoriteIcon;
67 // mainWebView is public static so it can be accessed from AboutDialog. It is also used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
68 public static WebView mainWebView;
70 // mainMenu is used in onCreateOptionsMenu() and onOptionsItemSelected().
71 private Menu mainMenu;
72 // formattedUrlString is used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
73 private String formattedUrlString;
74 // homepage is used in onCreate() and onOptionsItemSelected().
75 private String homepage;
76 // javaScriptEnabled is used in onCreate(), onCreateOptionsMenu(), onOptionsItemSelected(), and loadUrlFromTextBox().
77 private boolean javaScriptEnabled;
78 // domStorageEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
79 private boolean domStorageEnabled;
81 /* saveFormDataEnabled does nothing until database storage is implemented.
82 // saveFormDataEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
83 private boolean saveFormDataEnabled;
86 // cookieManager is used in onCreate() and onOptionsItemSelected().
87 private CookieManager cookieManager;
88 // cookiesEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
89 private boolean cookiesEnabled;
91 // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
92 private EditText urlTextBox;
95 // 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.
96 @SuppressLint("SetJavaScriptEnabled")
97 protected void onCreate(Bundle savedInstanceState) {
98 super.onCreate(savedInstanceState);
99 setContentView(R.layout.activity_webview);
101 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
102 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
103 setSupportActionBar(supportAppBar);
105 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
107 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
108 final ActionBar appBar = getSupportActionBar();
110 // Setup AdView for the free flavor.
111 final View adView = findViewById(R.id.adView);
113 // Implement swipe to refresh
114 final SwipeRefreshLayout swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
115 swipeToRefresh.setColorSchemeResources(R.color.blue);
116 swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
118 public void onRefresh() {
119 mainWebView.reload();
123 mainWebView = (WebView) findViewById(R.id.mainWebView);
125 if (appBar != null) {
126 // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
127 appBar.setCustomView(R.layout.url_bar);
128 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
130 // Set the "go" button on the keyboard to load the URL in urlTextBox.
131 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
132 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
133 public boolean onKey(View v, int keyCode, KeyEvent event) {
134 // If the event is a key-down event on the "enter" button, load the URL.
135 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
136 // Load the URL into the mainWebView and consume the event.
138 loadUrlFromTextBox();
139 } catch (UnsupportedEncodingException e) {
142 // If the enter key was pressed, consume the event.
145 // If any other key was pressed, do not consume the event.
152 mainWebView.setWebViewClient(new WebViewClient() {
153 // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
155 public boolean shouldOverrideUrlLoading(WebView view, String url) {
156 mainWebView.loadUrl(url);
160 // Update the URL in urlTextBox when the page starts to load.
162 public void onPageStarted(WebView view, String url, Bitmap favicon) {
163 urlTextBox.setText(url);
166 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
168 public void onPageFinished(WebView view, String url) {
169 formattedUrlString = url;
170 urlTextBox.setText(formattedUrlString);
174 mainWebView.setWebChromeClient(new WebChromeClient() {
175 // Update the progress bar when a page is loading.
177 public void onProgressChanged(WebView view, int progress) {
178 // Make sure that appBar is not null.
179 if (appBar != null) {
180 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
181 progressBar.setProgress(progress);
182 if (progress < 100) {
183 progressBar.setVisibility(View.VISIBLE);
185 progressBar.setVisibility(View.GONE);
187 //Stop the SwipeToRefresh indicator if it is running
188 swipeToRefresh.setRefreshing(false);
193 // Set the favorite icon when it changes.
195 public void onReceivedIcon(WebView view, Bitmap icon) {
196 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
199 // Place the favorite icon in the appBar if it is not null.
200 if (appBar != null) {
201 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
202 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
206 // Enter full screen video
208 public void onShowCustomView(View view, CustomViewCallback callback) {
209 if (appBar != null) {
213 // Show the fullScreenVideoFrameLayout.
214 fullScreenVideoFrameLayout.addView(view);
215 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
217 // Hide the mainWebView.
218 mainWebView.setVisibility(View.GONE);
220 // Hide the ad if this is the free flavor.
221 BannerAd.hideAd(adView);
223 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
224 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
225 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
228 // Set the one flag supported by API >= 14.
229 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
231 // Set the two flags that are supported by API >= 16.
232 if (Build.VERSION.SDK_INT >= 16) {
233 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
236 // Set all three flags that are supported by API >= 19.
237 if (Build.VERSION.SDK_INT >= 19) {
238 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
242 // Exit full screen video
243 public void onHideCustomView() {
244 if (appBar != null) {
248 // Show the mainWebView.
249 mainWebView.setVisibility(View.VISIBLE);
251 // Show the ad if this is the free flavor.
252 BannerAd.showAd(adView);
254 // Hide the fullScreenVideoFrameLayout.
255 fullScreenVideoFrameLayout.removeAllViews();
256 fullScreenVideoFrameLayout.setVisibility(View.GONE);
260 // Allow the downloading of files.
261 mainWebView.setDownloadListener(new DownloadListener() {
262 // Launch the Android download manager when a link leads to a download.
264 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
265 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
266 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
268 // Add the URL as the description for the download.
269 requestUri.setDescription(url);
271 // Show the download notification after the download is completed.
272 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
274 // Initiate the download and display a Snackbar.
275 downloadManager.enqueue(requestUri);
276 Snackbar.make(findViewById(R.id.mainWebView), R.string.download_started, Snackbar.LENGTH_SHORT).show();
280 // Allow pinch to zoom.
281 mainWebView.getSettings().setBuiltInZoomControls(true);
283 // Hide zoom controls.
284 mainWebView.getSettings().setDisplayZoomControls(false);
286 // Initialize the default preference values the first time the program is run.
287 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
289 // Get the shared preference values.
290 SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
292 // Set JavaScript initial status.
293 javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
294 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
296 // Set DOM storage initial status.
297 domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
298 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
300 /* Save Form Data does nothing until database storage is implemented.
301 // Set Save Form Data initial status.
302 saveFormDataEnabled = true;
303 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
306 // Set cookies initial status.
307 cookiesEnabled = savedPreferences.getBoolean("cookies_enabled", false);
308 cookieManager = CookieManager.getInstance();
309 cookieManager.setAcceptCookie(cookiesEnabled);
311 // Set homepage initial status.
312 homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
314 // Get the intent information that started the app.
315 final Intent intent = getIntent();
317 if (intent.getData() != null) {
318 // Get the intent data and convert it to a string.
319 final Uri intentUriData = intent.getData();
320 formattedUrlString = intentUriData.toString();
323 // If formattedUrlString is null assign the homepage to it.
324 if (formattedUrlString == null) {
325 formattedUrlString = homepage;
328 // Load the initial website.
329 mainWebView.loadUrl(formattedUrlString);
331 // Load the ad if this is the free flavor.
332 BannerAd.requestAd(adView);
336 protected void onNewIntent(Intent intent) {
337 // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
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();
347 mainWebView.loadUrl(formattedUrlString);
349 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
350 mainWebView.requestFocus();
354 public boolean onCreateOptionsMenu(Menu menu) {
355 // Inflate the menu; this adds items to the action bar if it is present.
356 getMenuInflater().inflate(R.menu.menu_webview, menu);
358 // Set mainMenu so it can be used by onOptionsItemSelected.
361 // Get MenuItems for checkable menu items.
362 MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
363 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
364 /* toggleSaveFormData does nothing until database storage is implemented.
365 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
367 MenuItem toggleCookies = menu.findItem(R.id.toggleCookies);
369 // Set the initial icon for toggleJavaScript
370 if (javaScriptEnabled) {
371 toggleJavaScript.setIcon(R.drawable.javascript_enabled);
373 if (domStorageEnabled || cookiesEnabled) {
374 toggleJavaScript.setIcon(R.drawable.warning);
376 toggleJavaScript.setIcon(R.drawable.privacy_mode);
380 // Set the initial status of the menu item checkboxes.
381 toggleDomStorage.setChecked(domStorageEnabled);
382 /* toggleSaveFormData does nothing until database storage is implemented.
383 toggleSaveFormData.setChecked(saveFormDataEnabled);
385 toggleCookies.setChecked(cookiesEnabled);
391 public boolean onPrepareOptionsMenu(Menu menu) {
392 // Enable Clear Cookies if there are any.
393 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
394 clearCookies.setEnabled(cookieManager.hasCookies());
396 // Enable Back if canGoBack().
397 MenuItem back = menu.findItem(R.id.back);
398 back.setEnabled(mainWebView.canGoBack());
400 // Enable forward if canGoForward().
401 MenuItem forward = menu.findItem(R.id.forward);
402 forward.setEnabled(mainWebView.canGoForward());
404 // Run all the other default commands.
405 super.onPrepareOptionsMenu(menu);
407 // return true displays the menu.
412 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
413 @SuppressLint("SetJavaScriptEnabled")
414 // removeAllCookies is deprecated, but it is required for API < 21.
415 @SuppressWarnings("deprecation")
416 public boolean onOptionsItemSelected(MenuItem menuItem) {
417 int menuItemId = menuItem.getItemId();
419 // Some options need to update the drawable for toggleJavaScript.
420 MenuItem toggleJavaScript = mainMenu.findItem(R.id.toggleJavaScript);
422 // Set the commands that relate to the menu entries.
423 switch (menuItemId) {
424 case R.id.toggleJavaScript:
425 if (javaScriptEnabled) {
426 javaScriptEnabled = false;
427 mainWebView.getSettings().setJavaScriptEnabled(false);
428 mainWebView.reload();
430 // Update the toggleJavaScript icon and display a snackbar.
431 if (domStorageEnabled || cookiesEnabled) {
432 menuItem.setIcon(R.drawable.warning);
433 if (domStorageEnabled && cookiesEnabled) {
434 Snackbar.make(findViewById(R.id.mainWebView), R.string.both_still_enabled, Snackbar.LENGTH_SHORT).show();
436 if (domStorageEnabled) {
437 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_still_enabled, Snackbar.LENGTH_SHORT).show();
439 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_still_enabled, Snackbar.LENGTH_SHORT).show();
443 menuItem.setIcon(R.drawable.privacy_mode);
444 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
447 javaScriptEnabled = true;
448 menuItem.setIcon(R.drawable.javascript_enabled);
449 mainWebView.getSettings().setJavaScriptEnabled(true);
450 mainWebView.reload();
451 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
455 case R.id.toggleDomStorage:
456 if (domStorageEnabled) {
457 domStorageEnabled = false;
458 menuItem.setChecked(false);
459 mainWebView.getSettings().setDomStorageEnabled(false);
460 mainWebView.reload();
462 // Update the toggleJavaScript icon and display a snackbar if appropriate.
463 if (!javaScriptEnabled && !cookiesEnabled) {
464 toggleJavaScript.setIcon(R.drawable.privacy_mode);
465 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
467 if (cookiesEnabled) {
468 toggleJavaScript.setIcon(R.drawable.warning);
469 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_still_enabled, Snackbar.LENGTH_SHORT).show();
470 } // Else Do nothing because JavaScript is enabled.
473 domStorageEnabled = true;
474 menuItem.setChecked(true);
475 mainWebView.getSettings().setDomStorageEnabled(true);
476 mainWebView.reload();
478 // Update the toggleJavaScript icon if appropriate.
479 if (!javaScriptEnabled) {
480 toggleJavaScript.setIcon(R.drawable.warning);
481 } // Else Do nothing because JavaScript is enabled.
483 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
487 /* toggleSaveFormData does nothing until database storage is implemented.
488 case R.id.toggleSaveFormData:
489 if (saveFormDataEnabled) {
490 saveFormDataEnabled = false;
491 menuItem.setChecked(false);
492 mainWebView.getSettings().setSaveFormData(false);
493 mainWebView.reload();
495 saveFormDataEnabled = true;
496 menuItem.setChecked(true);
497 mainWebView.getSettings().setSaveFormData(true);
498 mainWebView.reload();
503 case R.id.toggleCookies:
504 if (cookiesEnabled) {
505 cookiesEnabled = false;
506 menuItem.setChecked(false);
507 cookieManager.setAcceptCookie(false);
508 mainWebView.reload();
510 // Update the toggleJavaScript icon and display a snackbar if appropriate.
511 if (!javaScriptEnabled && !domStorageEnabled) {
512 toggleJavaScript.setIcon(R.drawable.privacy_mode);
513 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
515 if (domStorageEnabled) {
516 toggleJavaScript.setIcon(R.drawable.warning);
517 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
518 } // Else Do nothing because JavaScript is enabled.
521 cookiesEnabled = true;
522 menuItem.setChecked(true);
523 cookieManager.setAcceptCookie(true);
524 mainWebView.reload();
526 // Update the toggleJavaScript icon if appropriate.
527 if (!javaScriptEnabled) {
528 toggleJavaScript.setIcon(R.drawable.warning);
529 } // Else Do nothing because JavaScript is enabled.
531 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show();
535 case R.id.clearDomStorage:
536 WebStorage webStorage = WebStorage.getInstance();
537 webStorage.deleteAllData();
538 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
541 case R.id.clearCookies:
542 if (Build.VERSION.SDK_INT < 21) {
543 cookieManager.removeAllCookie();
545 cookieManager.removeAllCookies(null);
547 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
550 case R.id.addToHomescreen:
551 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
552 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
553 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
555 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
559 // Launch the system Download Manager.
560 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
562 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
563 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
565 startActivity(downloadManagerIntent);
569 mainWebView.loadUrl(homepage);
573 mainWebView.goBack();
577 mainWebView.goForward();
581 Intent shareIntent = new Intent();
582 shareIntent.setAction(Intent.ACTION_SEND);
583 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
584 shareIntent.setType("text/plain");
585 startActivity(Intent.createChooser(shareIntent, "Share URL"));
589 // Launch SettingsActivity.
590 Intent intent = new Intent(this, SettingsActivity.class);
591 startActivity(intent);
595 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
596 AppCompatDialogFragment aboutDialog = new AboutDialog();
597 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
600 case R.id.clearAndExit:
601 // Clear DOM storage.
602 WebStorage domStorage = WebStorage.getInstance();
603 domStorage.deleteAllData();
605 // Clear cookies. The commands changed slightly in API 21.
606 if (Build.VERSION.SDK_INT >= 21) {
607 cookieManager.removeAllCookies(null);
609 cookieManager.removeAllCookie();
612 // Destroy the internal state of the webview.
613 mainWebView.destroy();
615 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
616 if (Build.VERSION.SDK_INT >= 21) {
617 finishAndRemoveTask();
624 return super.onOptionsItemSelected(menuItem);
629 public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
630 // Do nothing because the user selected "Cancel".
634 public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
635 // Get shortcutNameEditText from the alert dialog.
636 EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
638 // Create the bookmark shortcut based on formattedUrlString.
639 Intent bookmarkShortcut = new Intent();
640 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
641 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
643 // Place the bookmark shortcut on the home screen.
644 Intent placeBookmarkShortcut = new Intent();
645 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
646 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
647 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
648 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
649 sendBroadcast(placeBookmarkShortcut);
652 // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
654 public void onBackPressed() {
655 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
657 if (mainWebView.canGoBack()) {
658 mainWebView.goBack();
660 super.onBackPressed();
664 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
665 // Get the text from urlTextBox and convert it to a string.
666 String unformattedUrlString = urlTextBox.getText().toString();
667 URL unformattedUrl = null;
668 Uri.Builder formattedUri = new Uri.Builder();
670 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
671 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
672 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
673 if (!unformattedUrlString.startsWith("http")) {
674 unformattedUrlString = "http://" + unformattedUrlString;
677 // 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.
679 unformattedUrl = new URL(unformattedUrlString);
680 } catch (MalformedURLException e) {
684 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
685 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
686 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
687 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
688 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
689 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
691 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
692 formattedUrlString = formattedUri.build().toString();
694 // Sanitize the search input and convert it to a DuckDuckGo search.
695 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
697 // Use the correct search URL based on javaScriptEnabled.
698 if (javaScriptEnabled) {
699 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
701 formattedUrlString = "https://duckduckgo.com/html/?q=" + encodedUrlString;
705 mainWebView.loadUrl(formattedUrlString);
707 // Hides the keyboard so we can see the webpage.
708 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
709 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);