2 * Copyright 2015-2016 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of 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.v4.app.DialogFragment;
34 import android.support.v4.widget.SwipeRefreshLayout;
35 import android.support.v7.app.ActionBar;
36 import android.support.v7.app.AppCompatActivity;
37 import android.support.v7.app.AppCompatDialogFragment;
38 import android.support.v7.widget.Toolbar;
39 import android.util.Patterns;
40 import android.view.KeyEvent;
41 import android.view.Menu;
42 import android.view.MenuItem;
43 import android.view.View;
44 import android.view.inputmethod.InputMethodManager;
45 import android.webkit.CookieManager;
46 import android.webkit.DownloadListener;
47 import android.webkit.WebChromeClient;
48 import android.webkit.WebStorage;
49 import android.webkit.WebView;
50 import android.webkit.WebViewClient;
51 import android.widget.EditText;
52 import android.widget.FrameLayout;
53 import android.widget.ImageView;
54 import android.widget.ProgressBar;
55 import android.widget.Toast;
57 import com.google.android.gms.ads.AdRequest;
58 import com.google.android.gms.ads.AdView;
60 import java.io.UnsupportedEncodingException;
61 import java.net.MalformedURLException;
63 import java.net.URLEncoder;
65 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
66 public class MainWebViewActivity extends AppCompatActivity implements CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener {
67 // favoriteIcon is public static so it can be accessed from CreateHomeScreenShortcut.
68 public static Bitmap favoriteIcon;
69 // mainWebView is public static so it can be accessed from AboutDialog. It is also used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
70 public static WebView mainWebView;
72 // mainMenu is used in onCreateOptionsMenu() and onOptionsItemSelected().
73 private Menu mainMenu;
74 // formattedUrlString is used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
75 private String formattedUrlString;
76 // homepage is used in onCreate() and onOptionsItemSelected().
77 private String homepage;
78 // javaScriptEnabled is used in onCreate(), onCreateOptionsMenu(), onOptionsItemSelected(), and loadUrlFromTextBox().
79 private boolean javaScriptEnabled;
80 // domStorageEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
81 private boolean domStorageEnabled;
83 /* saveFormDataEnabled does nothing until database storage is implemented.
84 // saveFormDataEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
85 private boolean saveFormDataEnabled;
88 // cookieManager is used in onCreate() and onOptionsItemSelected().
89 private CookieManager cookieManager;
90 // cookiesEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
91 private boolean cookiesEnabled;
93 // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
94 private EditText urlTextBox;
97 // 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.
98 @SuppressLint("SetJavaScriptEnabled")
99 protected void onCreate(Bundle savedInstanceState) {
100 super.onCreate(savedInstanceState);
101 setContentView(R.layout.activity_webview);
103 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
104 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
105 setSupportActionBar(supportAppBar);
107 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
108 final Activity mainWebViewActivity = this;
109 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
110 final ActionBar appBar = getSupportActionBar();
112 // Setup the AdView for the free flavor.
113 final AdView adView = (AdView) findViewById(R.id.adView);
115 // Implement swipe to refresh
116 final SwipeRefreshLayout swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
117 swipeToRefresh.setColorSchemeResources(R.color.blue);
118 swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
120 public void onRefresh() {
121 mainWebView.reload();
125 mainWebView = (WebView) findViewById(R.id.mainWebView);
127 if (appBar != null) {
128 // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
129 appBar.setCustomView(R.layout.url_bar);
130 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
132 // Set the "go" button on the keyboard to load the URL in urlTextBox.
133 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
134 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
135 public boolean onKey(View v, int keyCode, KeyEvent event) {
136 // If the event is a key-down event on the "enter" button, load the URL.
137 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
138 // Load the URL into the mainWebView and consume the event.
140 loadUrlFromTextBox();
141 } catch (UnsupportedEncodingException e) {
144 // If the enter key was pressed, consume the event.
147 // If any other key was pressed, do not consume the event.
154 mainWebView.setWebViewClient(new WebViewClient() {
155 // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
157 public boolean shouldOverrideUrlLoading(WebView view, String url) {
158 mainWebView.loadUrl(url);
162 /* These errors do not provide any useful information and clutter the screen.
163 public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
164 Toast.makeText(mainWebViewActivity, "Error loading " + request + " Error: " + error, Toast.LENGTH_SHORT).show();
168 // Update the URL in urlTextBox when the page starts to load.
170 public void onPageStarted(WebView view, String url, Bitmap favicon) {
171 urlTextBox.setText(url);
174 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
176 public void onPageFinished(WebView view, String url) {
177 formattedUrlString = url;
178 urlTextBox.setText(formattedUrlString);
182 mainWebView.setWebChromeClient(new WebChromeClient() {
183 // Update the progress bar when a page is loading.
185 public void onProgressChanged(WebView view, int progress) {
186 // Make sure that appBar is not null.
187 if (appBar != null) {
188 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
189 progressBar.setProgress(progress);
190 if (progress < 100) {
191 progressBar.setVisibility(View.VISIBLE);
193 progressBar.setVisibility(View.GONE);
195 //Stop the SwipeToRefresh indicator if it is running
196 swipeToRefresh.setRefreshing(false);
201 // Set the favorite icon when it changes.
203 public void onReceivedIcon(WebView view, Bitmap icon) {
204 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
207 // Place the favorite icon in the appBar if it is not null.
208 if (appBar != null) {
209 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
210 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
214 // Enter full screen video
216 public void onShowCustomView(View view, CustomViewCallback callback) {
217 if (appBar != null) {
221 // Show the fullScreenVideoFrameLayout.
222 fullScreenVideoFrameLayout.addView(view);
223 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
225 // Hide the mainWebView.
226 mainWebView.setVisibility(View.GONE);
228 // Hide the add if this is the free flavor.
229 if (getString(R.string.free_flavor).equals("true")) {
230 adView.setVisibility(View.GONE);
233 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
234 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
235 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
238 // Set the one flag supported by API >= 14.
239 if (Build.VERSION.SDK_INT >= 14) {
240 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
243 // Set the two flags that are supported by API >= 16.
244 if (Build.VERSION.SDK_INT >= 16) {
245 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
248 // Set all three flags that are supported by API >= 19.
249 if (Build.VERSION.SDK_INT >= 19) {
250 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
254 // Exit full screen video
255 public void onHideCustomView() {
256 if (appBar != null) {
260 // Show the mainWebView.
261 mainWebView.setVisibility(View.VISIBLE);
263 // Show the adView if this is the free flavor.
264 if (getString(R.string.free_flavor).equals("true")) {
265 adView.setVisibility(View.VISIBLE);
268 // Hide the fullScreenVideoFrameLayout.
269 fullScreenVideoFrameLayout.removeAllViews();
270 fullScreenVideoFrameLayout.setVisibility(View.GONE);
274 // Allow the downloading of files.
275 mainWebView.setDownloadListener(new DownloadListener() {
276 // Launch the Android download manager when a link leads to a download.
278 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
279 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
280 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
282 // Add the URL as the description for the download.
283 requestUri.setDescription(url);
285 // Show the download notification after the download is completed if the API is 11 or greater.
286 if (Build.VERSION.SDK_INT >= 11) {
287 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
290 downloadManager.enqueue(requestUri);
291 Toast.makeText(mainWebViewActivity, "Download started", Toast.LENGTH_SHORT).show();
295 // Allow pinch to zoom.
296 mainWebView.getSettings().setBuiltInZoomControls(true);
298 // Hide zoom controls if the API is 11 or greater.
299 if (Build.VERSION.SDK_INT >= 11) {
300 mainWebView.getSettings().setDisplayZoomControls(false);
303 // Initialize the default preference values the first time the program is run.
304 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
306 // Get the shared preference values.
307 SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
309 // Set JavaScript initial status.
310 javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
311 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
313 // Set DOM storage initial status.
314 domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
315 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
317 /* Save Form Data does nothing until database storage is implemented.
318 // Set Save Form Data initial status.
319 saveFormDataEnabled = true;
320 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
323 // Set cookies initial status.
324 cookiesEnabled = savedPreferences.getBoolean("cookies_enabled", false);
325 cookieManager = CookieManager.getInstance();
326 cookieManager.setAcceptCookie(cookiesEnabled);
328 // Set hompage initial status.
329 homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
331 // Get the intent information that started the app.
332 final Intent intent = getIntent();
334 if (intent.getData() != null) {
335 // Get the intent data and convert it to a string.
336 final Uri intentUriData = intent.getData();
337 formattedUrlString = intentUriData.toString();
340 // If formattedUrlString is null assign the homepage to it.
341 if (formattedUrlString == null) {
342 formattedUrlString = homepage;
345 // Load the initial website.
346 mainWebView.loadUrl(formattedUrlString);
348 // Load the ad if this is the free flavor.
349 if (getString(R.string.free_flavor).equals("true")) {
350 AdRequest adRequest = new AdRequest.Builder().build();
351 adView.loadAd(adRequest);
356 protected void onNewIntent(Intent intent) {
357 // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
360 if (intent.getData() != null) {
361 // Get the intent data and convert it to a string.
362 final Uri intentUriData = intent.getData();
363 formattedUrlString = intentUriData.toString();
367 mainWebView.loadUrl(formattedUrlString);
369 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
370 mainWebView.requestFocus();
374 public boolean onCreateOptionsMenu(Menu menu) {
375 // Inflate the menu; this adds items to the action bar if it is present.
376 getMenuInflater().inflate(R.menu.menu_webview, menu);
378 // Set mainMenu so it can be used by onOptionsItemSelected.
381 // Get MenuItems for checkable menu items.
382 MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
383 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
384 /* toggleSaveFormData does nothing until database storage is implemented.
385 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
387 MenuItem toggleCookies = menu.findItem(R.id.toggleCookies);
389 // Set the initial icon for toggleJavaScript
390 if (javaScriptEnabled) {
391 toggleJavaScript.setIcon(R.drawable.javascript_enabled);
393 if (domStorageEnabled || cookiesEnabled) {
394 toggleJavaScript.setIcon(R.drawable.warning);
396 toggleJavaScript.setIcon(R.drawable.privacy_mode);
400 // Set the initial status of the menu item checkboxes.
401 toggleDomStorage.setChecked(domStorageEnabled);
402 /* toggleSaveFormData does nothing until database storage is implemented.
403 toggleSaveFormData.setChecked(saveFormDataEnabled);
405 toggleCookies.setChecked(cookiesEnabled);
411 public boolean onPrepareOptionsMenu(Menu menu) {
412 // Enable Clear Cookies if there are any.
413 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
414 clearCookies.setEnabled(cookieManager.hasCookies());
416 // Enable Back if canGoBack().
417 MenuItem back = menu.findItem(R.id.back);
418 back.setEnabled(mainWebView.canGoBack());
420 // Enable forward if canGoForward().
421 MenuItem forward = menu.findItem(R.id.forward);
422 forward.setEnabled(mainWebView.canGoForward());
424 // Run all the other default commands.
425 super.onPrepareOptionsMenu(menu);
427 // return true displays the menu.
432 // @TargetApi(11) turns off the errors regarding copy and paste, which are removed from view in menu_webview.xml for lower version of Android.
434 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
435 @SuppressLint("SetJavaScriptEnabled")
436 // removeAllCookies is deprecated, but it is required for API < 21.
437 @SuppressWarnings("deprecation")
438 public boolean onOptionsItemSelected(MenuItem menuItem) {
439 int menuItemId = menuItem.getItemId();
441 // Some options need to update the drawable for toggleJavaScript.
442 MenuItem toggleJavaScript = mainMenu.findItem(R.id.toggleJavaScript);
444 // Set the commands that relate to the menu entries.
445 switch (menuItemId) {
446 case R.id.toggleJavaScript:
447 if (javaScriptEnabled) {
448 javaScriptEnabled = false;
449 mainWebView.getSettings().setJavaScriptEnabled(false);
450 mainWebView.reload();
452 // Update the toggleJavaScript icon and display a toast message.
453 if (domStorageEnabled || cookiesEnabled) {
454 menuItem.setIcon(R.drawable.warning);
455 if (domStorageEnabled && cookiesEnabled) {
456 Toast.makeText(getApplicationContext(), "JavaScript disabled, DOM Storage and Cookies still enabled", Toast.LENGTH_SHORT).show();
458 if (domStorageEnabled) {
459 Toast.makeText(getApplicationContext(), "JavaScript disabled, DOM Storage still enabled", Toast.LENGTH_SHORT).show();
461 Toast.makeText(getApplicationContext(), "JavaScript disabled, Cookies still enabled", Toast.LENGTH_SHORT).show();
465 menuItem.setIcon(R.drawable.privacy_mode);
466 Toast.makeText(getApplicationContext(), R.string.privacy_mode, Toast.LENGTH_SHORT).show();
469 javaScriptEnabled = true;
470 menuItem.setIcon(R.drawable.javascript_enabled);
471 mainWebView.getSettings().setJavaScriptEnabled(true);
472 mainWebView.reload();
473 Toast.makeText(getApplicationContext(), "JavaScript enabled", Toast.LENGTH_SHORT).show();
477 case R.id.toggleDomStorage:
478 if (domStorageEnabled) {
479 domStorageEnabled = false;
480 menuItem.setChecked(false);
481 mainWebView.getSettings().setDomStorageEnabled(false);
482 mainWebView.reload();
484 // Update the toggleJavaScript icon and display a toast message if appropriate.
485 if (!javaScriptEnabled && !cookiesEnabled) {
486 toggleJavaScript.setIcon(R.drawable.privacy_mode);
487 Toast.makeText(getApplicationContext(), R.string.privacy_mode, Toast.LENGTH_SHORT).show();
489 if (cookiesEnabled) {
490 toggleJavaScript.setIcon(R.drawable.warning);
491 Toast.makeText(getApplicationContext(), "Cookies still enabled", Toast.LENGTH_SHORT).show();
492 } // Else Do nothing because JavaScript is enabled.
495 domStorageEnabled = true;
496 menuItem.setChecked(true);
497 mainWebView.getSettings().setDomStorageEnabled(true);
498 mainWebView.reload();
500 // Update the toggleJavaScript icon if appropriate.
501 if (!javaScriptEnabled) {
502 toggleJavaScript.setIcon(R.drawable.warning);
503 } // Else Do nothing because JavaScript is enabled.
505 Toast.makeText(getApplicationContext(), "DOM Storage enabled", Toast.LENGTH_SHORT).show();
509 /* toggleSaveFormData does nothing until database storage is implemented.
510 case R.id.toggleSaveFormData:
511 if (saveFormDataEnabled) {
512 saveFormDataEnabled = false;
513 menuItem.setChecked(false);
514 mainWebView.getSettings().setSaveFormData(false);
515 mainWebView.reload();
517 saveFormDataEnabled = true;
518 menuItem.setChecked(true);
519 mainWebView.getSettings().setSaveFormData(true);
520 mainWebView.reload();
525 case R.id.toggleCookies:
526 if (cookiesEnabled) {
527 cookiesEnabled = false;
528 menuItem.setChecked(false);
529 cookieManager.setAcceptCookie(false);
530 mainWebView.reload();
532 // Update the toggleJavaScript icon and display a toast message if appropriate.
533 if (!javaScriptEnabled && !domStorageEnabled) {
534 toggleJavaScript.setIcon(R.drawable.privacy_mode);
535 Toast.makeText(getApplicationContext(), R.string.privacy_mode, Toast.LENGTH_SHORT).show();
537 if (domStorageEnabled) {
538 toggleJavaScript.setIcon(R.drawable.warning);
539 Toast.makeText(getApplicationContext(), "DOM Storage still enabled", Toast.LENGTH_SHORT).show();
540 } // Else Do nothing because JavaScript is enabled.
543 cookiesEnabled = true;
544 menuItem.setChecked(true);
545 cookieManager.setAcceptCookie(true);
546 mainWebView.reload();
548 // Update the toggleJavaScript icon if appropriate.
549 if (!javaScriptEnabled) {
550 toggleJavaScript.setIcon(R.drawable.warning);
551 } // Else Do nothing because JavaScript is enabled.
553 Toast.makeText(getApplicationContext(), "Cookies enabled", Toast.LENGTH_SHORT).show();
557 case R.id.clearDomStorage:
558 WebStorage webStorage = WebStorage.getInstance();
559 webStorage.deleteAllData();
560 Toast.makeText(getApplicationContext(), "DOM storage deleted", Toast.LENGTH_SHORT).show();
563 case R.id.clearCookies:
564 if (Build.VERSION.SDK_INT < 21) {
565 cookieManager.removeAllCookie();
567 cookieManager.removeAllCookies(null);
569 Toast.makeText(getApplicationContext(), "Cookies deleted", Toast.LENGTH_SHORT).show();
572 case R.id.addToHomescreen:
573 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
574 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
575 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
577 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
581 // Launch the system Download Manager.
582 Intent downloadManangerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
584 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
585 downloadManangerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
587 startActivity(downloadManangerIntent);
591 mainWebView.loadUrl(homepage);
595 mainWebView.goBack();
599 mainWebView.goForward();
603 Intent shareIntent = new Intent();
604 shareIntent.setAction(Intent.ACTION_SEND);
605 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
606 shareIntent.setType("text/plain");
607 startActivity(Intent.createChooser(shareIntent, "Share URL"));
611 // Launch SettingsActivity.
612 Intent intent = new Intent(this, SettingsActivity.class);
613 startActivity(intent);
617 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
618 AppCompatDialogFragment aboutDialog = new AboutDialog();
619 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
622 case R.id.clearAndExit:
623 // Clear DOM storage.
624 WebStorage domStorage = WebStorage.getInstance();
625 domStorage.deleteAllData();
627 // Clear cookies. The commands changed slightly in API 21.
628 if (Build.VERSION.SDK_INT >= 21) {
629 cookieManager.removeAllCookies(null);
631 cookieManager.removeAllCookie();
634 // Destroy the internal state of the webview.
635 mainWebView.destroy();
637 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
638 if (Build.VERSION.SDK_INT >= 21) {
639 finishAndRemoveTask();
646 return super.onOptionsItemSelected(menuItem);
651 public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
652 // Do nothing because the user selected "Cancel".
656 public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
657 // Get shortcutNameEditText from the alert dialog.
658 EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
660 // Create the bookmark shortcut based on formattedUrlString.
661 Intent bookmarkShortcut = new Intent();
662 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
663 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
665 // Place the bookmark shortcut on the home screen.
666 Intent placeBookmarkShortcut = new Intent();
667 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
668 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
669 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
670 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
671 sendBroadcast(placeBookmarkShortcut);
674 // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
676 public void onBackPressed() {
677 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
679 if (mainWebView.canGoBack()) {
680 mainWebView.goBack();
682 super.onBackPressed();
686 public void loadUrlFromTextBox() throws UnsupportedEncodingException {
687 // Get the text from urlTextBox and convert it to a string.
688 String unformattedUrlString = urlTextBox.getText().toString();
689 URL unformattedUrl = null;
690 Uri.Builder formattedUri = new Uri.Builder();
692 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
693 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
694 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
695 if (!unformattedUrlString.startsWith("http")) {
696 unformattedUrlString = "http://" + unformattedUrlString;
699 // 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.
701 unformattedUrl = new URL(unformattedUrlString);
702 } catch (MalformedURLException e) {
706 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
707 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
708 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
709 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
710 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
711 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
713 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
714 formattedUrlString = formattedUri.build().toString();
716 // Sanitize the search input and convert it to a DuckDuckGo search.
717 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
719 // Use the correct search URL based on javaScriptEnabled.
720 if (javaScriptEnabled) {
721 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
723 formattedUrlString = "https://duckduckgo.com/html/?q=" + encodedUrlString;
727 mainWebView.loadUrl(formattedUrlString);
729 // Hides the keyboard so we can see the webpage.
730 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
731 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);