2 * Copyright 2015-2016 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
6 * Privacy Browser is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * Privacy Browser is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
20 package com.stoutner.privacybrowser;
22 import android.annotation.SuppressLint;
23 import android.app.Activity;
24 import android.app.DialogFragment;
25 import android.app.DownloadManager;
26 import android.content.Intent;
27 import android.content.SharedPreferences;
28 import android.content.res.Configuration;
29 import android.graphics.Bitmap;
30 import android.graphics.drawable.BitmapDrawable;
31 import android.graphics.drawable.Drawable;
32 import android.net.Uri;
33 import android.net.http.SslError;
34 import android.os.Build;
35 import android.os.Bundle;
36 import android.preference.PreferenceManager;
37 import android.support.design.widget.NavigationView;
38 import android.support.design.widget.Snackbar;
39 import android.support.v4.app.ActivityCompat;
40 import android.support.v4.content.ContextCompat;
41 import android.support.v4.view.GravityCompat;
42 import android.support.v4.widget.DrawerLayout;
43 import android.support.v4.widget.SwipeRefreshLayout;
44 import android.support.v7.app.ActionBar;
45 import android.support.v7.app.ActionBarDrawerToggle;
46 import android.support.v7.app.AppCompatActivity;
47 import android.support.v7.widget.Toolbar;
48 import android.util.Patterns;
49 import android.view.KeyEvent;
50 import android.view.Menu;
51 import android.view.MenuItem;
52 import android.view.View;
53 import android.view.inputmethod.InputMethodManager;
54 import android.webkit.CookieManager;
55 import android.webkit.DownloadListener;
56 import android.webkit.SslErrorHandler;
57 import android.webkit.WebChromeClient;
58 import android.webkit.WebStorage;
59 import android.webkit.WebView;
60 import android.webkit.WebViewClient;
61 import android.webkit.WebViewDatabase;
62 import android.widget.EditText;
63 import android.widget.FrameLayout;
64 import android.widget.ImageView;
65 import android.widget.ProgressBar;
67 import java.io.UnsupportedEncodingException;
68 import java.net.MalformedURLException;
70 import java.net.URLEncoder;
71 import java.util.HashMap;
74 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
75 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener,
76 SslCertificateError.SslCertificateErrorListener, DownloadFile.DownloadFileListener {
77 // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `BookmarksActivity`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
78 // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
79 public static Bitmap favoriteIcon;
81 // `privacyBrowserActivity` is public static so it can be accessed from `SettingsFragment`.
82 // It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `onOptionsItemSelected()`,
83 public static Activity privacyBrowserActivity;
85 // `mainWebView` is public static so it can be accessed from `SettingsFragment`.
86 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, and `loadUrlFromTextBox()`.
87 public static WebView mainWebView;
89 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`.
90 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
91 public static String formattedUrlString;
93 // `mainMenu` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreateOptionsMenu()` and `onOptionsItemSelected()`.
94 public static Menu mainMenu;
96 // `cookieManager` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
97 public static CookieManager cookieManager;
99 // `javaScriptEnabled` is public static so it can be accessed from `SettingsFragment`.
100 // It is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
101 public static boolean javaScriptEnabled;
103 // `firstPartyCookiesEnabled` is public static so it can be accessed from `SettingsFragment`.
104 // It is also used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, and `onOptionsItemSelected()`.
105 public static boolean firstPartyCookiesEnabled;
107 // `thirdPartyCookiesEnables` is public static so it can be accessed from `SettingsFragment`.
108 // It is also used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, and `onOptionsItemSelected()`.
109 public static boolean thirdPartyCookiesEnabled;
111 // `domStorageEnabled` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `onOptionsItemSelected()`.
112 public static boolean domStorageEnabled;
114 // `saveFormDataEnabled` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `onOptionsItemSelected()`.
115 public static boolean saveFormDataEnabled;
117 // `javaScriptDisabledSearchURL` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()` and `loadURLFromTextBox()`.
118 public static String javaScriptDisabledSearchURL;
120 // `javaScriptEnabledSearchURL` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()` and `loadURLFromTextBox()`.
121 public static String javaScriptEnabledSearchURL;
123 // `homepage` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()` and `onOptionsItemSelected()`.
124 public static String homepage;
126 // `swipeToRefresh` is public static so it can be accessed from SettingsFragment. It is also used in onCreate().
127 public static SwipeRefreshLayout swipeToRefresh;
129 // `swipeToRefreshEnabled` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()`.
130 public static boolean swipeToRefreshEnabled;
132 // `customHeader` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
133 public static Map<String, String> customHeaders = new HashMap<String, String>();
137 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
138 private ActionBarDrawerToggle drawerToggle;
140 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
141 private DrawerLayout drawerLayout;
143 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
144 private EditText urlTextBox;
146 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
149 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
150 private SslErrorHandler sslErrorHandler;
152 // `sharedPreferences` is used in `onCreate()` and `onCreateOptionsMenu()`.
153 SharedPreferences sharedPreferences;
156 // 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.
157 @SuppressLint("SetJavaScriptEnabled")
158 protected void onCreate(Bundle savedInstanceState) {
159 super.onCreate(savedInstanceState);
160 setContentView(R.layout.main_coordinatorlayout);
162 // We need a handle for the activity, which is accessed from `SettingsFragment` and fed into `updatePrivacyIcons()`.
163 privacyBrowserActivity = this;
165 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
166 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
167 setSupportActionBar(supportAppBar);
168 final ActionBar appBar = getSupportActionBar();
170 // This is needed to get rid of the Android Studio warning that appBar might be null.
171 assert appBar != null;
173 // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
174 appBar.setCustomView(R.layout.url_bar);
175 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
177 // Set the "go" button on the keyboard to load the URL in urlTextBox.
178 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
179 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
180 public boolean onKey(View v, int keyCode, KeyEvent event) {
181 // If the event is a key-down event on the "enter" button, load the URL.
182 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
183 // Load the URL into the mainWebView and consume the event.
185 loadUrlFromTextBox();
186 } catch (UnsupportedEncodingException e) {
189 // If the enter key was pressed, consume the event.
192 // If any other key was pressed, do not consume the event.
198 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
200 // Implement swipe to refresh
201 swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
202 assert swipeToRefresh != null; //This assert removes the incorrect warning on the following line that swipeToRefresh might be null.
203 swipeToRefresh.setColorSchemeResources(R.color.blue);
204 swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
206 public void onRefresh() {
207 mainWebView.reload();
211 mainWebView = (WebView) findViewById(R.id.mainWebView);
213 // Create the navigation drawer.
214 drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
215 // The DrawerTitle identifies the drawer in accessibility mode.
216 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
218 // Listen for touches on the navigation menu.
219 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
220 assert navigationView != null; // This assert removes the incorrect warning on the following line that navigationView might be null.
221 navigationView.setNavigationItemSelectedListener(this);
223 // drawerToggle creates the hamburger icon at the start of the AppBar.
224 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
226 mainWebView.setWebViewClient(new WebViewClient() {
227 // shouldOverrideUrlLoading makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
229 public boolean shouldOverrideUrlLoading(WebView view, String url) {
230 // Use an external email program if the link begins with "mailto:".
231 if (url.startsWith("mailto:")) {
232 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
233 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
235 // Parse the url and set it as the data for the `Intent`.
236 emailIntent.setData(Uri.parse(url));
238 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
239 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
242 startActivity(emailIntent);
244 } else { // Load the URL in Privacy Browser.
245 mainWebView.loadUrl(url, customHeaders);
250 // Update the URL in urlTextBox when the page starts to load.
252 public void onPageStarted(WebView view, String url, Bitmap favicon) {
253 urlTextBox.setText(url);
256 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
258 public void onPageFinished(WebView view, String url) {
259 formattedUrlString = url;
261 // Only update urlTextBox if the user is not typing in it.
262 if (!urlTextBox.hasFocus()) {
263 urlTextBox.setText(formattedUrlString);
267 // Handle SSL Certificate errors.
269 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
270 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
271 sslErrorHandler = handler;
273 // Display the SSL error `AlertDialog`.
274 DialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
275 sslCertificateErrorDialogFragment.show(getFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
279 mainWebView.setWebChromeClient(new WebChromeClient() {
280 // Update the progress bar when a page is loading.
282 public void onProgressChanged(WebView view, int progress) {
283 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
284 progressBar.setProgress(progress);
285 if (progress < 100) {
286 progressBar.setVisibility(View.VISIBLE);
288 progressBar.setVisibility(View.GONE);
290 //Stop the SwipeToRefresh indicator if it is running
291 swipeToRefresh.setRefreshing(false);
295 // Set the favorite icon when it changes.
297 public void onReceivedIcon(WebView view, Bitmap icon) {
298 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
301 // Place the favorite icon in the appBar.
302 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
303 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
306 // Enter full screen video
308 public void onShowCustomView(View view, CustomViewCallback callback) {
311 // Show the fullScreenVideoFrameLayout.
312 assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
313 fullScreenVideoFrameLayout.addView(view);
314 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
316 // Hide the mainWebView.
317 mainWebView.setVisibility(View.GONE);
319 // Hide the ad if this is the free flavor.
320 BannerAd.hideAd(adView);
322 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
323 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
324 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
326 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
329 // Exit full screen video
330 public void onHideCustomView() {
333 // Show the mainWebView.
334 mainWebView.setVisibility(View.VISIBLE);
336 // Show the ad if this is the free flavor.
337 BannerAd.showAd(adView);
339 // Hide the fullScreenVideoFrameLayout.
340 assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
341 fullScreenVideoFrameLayout.removeAllViews();
342 fullScreenVideoFrameLayout.setVisibility(View.GONE);
346 // Allow the downloading of files.
347 mainWebView.setDownloadListener(new DownloadListener() {
349 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
350 // Show the `DownloadFile` `AlertDialog` and name this instance `@string/download`.
351 DialogFragment downloadFileDialogFragment = DownloadFile.fromUrl(url, contentDisposition, contentLength);
352 downloadFileDialogFragment.show(getFragmentManager(), getResources().getString(R.string.file_download));
356 // Allow pinch to zoom.
357 mainWebView.getSettings().setBuiltInZoomControls(true);
359 // Hide zoom controls.
360 mainWebView.getSettings().setDisplayZoomControls(false);
363 // Initialize the default preference values the first time the program is run.
364 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
366 // Get the shared preference values.
367 sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
369 // Set JavaScript initial status. The default value is false.
370 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
371 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
373 // Initialize cookieManager.
374 cookieManager = CookieManager.getInstance();
376 // Set cookies initial status. The default value is false.
377 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
378 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
380 // Set third-party cookies initial status if API >= 21. The default value is false.
381 if (Build.VERSION.SDK_INT >= 21) {
382 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
383 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
386 // Set DOM storage initial status. The default value is false.
387 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
388 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
390 // Set the saved form data initial status. The default is false.
391 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
392 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
394 // Set the user agent initial status.
395 String userAgentString = sharedPreferences.getString("user_agent", "Default user agent");
396 switch (userAgentString) {
397 case "Default user agent":
401 case "Custom user agent":
402 // Set the custom user agent on mainWebView, The default is "PrivacyBrowser/1.0".
403 mainWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0"));
407 // Set the selected user agent on mainWebView. The default is "PrivacyBrowser/1.0".
408 mainWebView.getSettings().setUserAgentString(sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0"));
412 // Set the initial string for JavaScript disabled search.
413 if (sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=").equals("Custom URL")) {
414 // Get the custom URL string. The default is "".
415 javaScriptDisabledSearchURL = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
417 // Use the string from javascript_disabled_search.
418 javaScriptDisabledSearchURL = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
421 // Set the initial string for JavaScript enabled search.
422 if (sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=").equals("Custom URL")) {
423 // Get the custom URL string. The default is "".
424 javaScriptEnabledSearchURL = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
426 // Use the string from javascript_enabled_search.
427 javaScriptEnabledSearchURL = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
431 // Set the homepage initial status. The default value is `https://www.duckduckgo.com`.
432 homepage = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
434 // Set the font size initial status. the default value is `100`.
435 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
436 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
438 // Set the swipe to refresh initial status. The default is `true`.
439 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", true);
440 swipeToRefresh.setEnabled(swipeToRefreshEnabled);
443 // Replace the header that `WebView` creates for `X-Requested-With` with a null value. The default value is the application ID (com.stoutner.privacybrowser.standard).
444 customHeaders.put("X-Requested-With", "");
446 // Set Do Not Track. The default is true.
447 if (sharedPreferences.getBoolean("do_not_track", true)) {
448 customHeaders.put("DNT", "1");
452 // Get the intent information that started the app.
453 final Intent intent = getIntent();
455 if (intent.getData() != null) {
456 // Get the intent data and convert it to a string.
457 final Uri intentUriData = intent.getData();
458 formattedUrlString = intentUriData.toString();
461 // If formattedUrlString is null assign the homepage to it.
462 if (formattedUrlString == null) {
463 formattedUrlString = homepage;
466 // Load the initial website.
467 mainWebView.loadUrl(formattedUrlString, customHeaders);
469 // If the favorite icon is null, load the default.
470 if (favoriteIcon == null) {
471 // We have to use `ContextCompat` until API >= 21.
472 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
473 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
474 favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
477 // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing.
478 adView = findViewById(R.id.adView);
479 BannerAd.requestAd(adView);
484 protected void onNewIntent(Intent intent) {
485 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
488 if (intent.getData() != null) {
489 // Get the intent data and convert it to a string.
490 final Uri intentUriData = intent.getData();
491 formattedUrlString = intentUriData.toString();
494 // Close the navigation drawer if it is open.
495 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
496 drawerLayout.closeDrawer(GravityCompat.START);
500 mainWebView.loadUrl(formattedUrlString, customHeaders);
502 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
503 mainWebView.requestFocus();
507 public boolean onCreateOptionsMenu(Menu menu) {
508 // Inflate the menu; this adds items to the action bar if it is present.
509 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
511 // Set mainMenu so it can be used by onOptionsItemSelected.
514 // Set the initial status of the privacy icon.
515 updatePrivacyIcons(privacyBrowserActivity);
517 // Get handles for the menu items.
518 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
519 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
520 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
521 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
523 // Set the initial status of the menu item checkboxes.
524 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
525 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
526 toggleDomStorage.setChecked(domStorageEnabled);
527 toggleSaveFormData.setChecked(saveFormDataEnabled);
529 // Set the status of the additional app bar icons. The default is `false`.
530 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
531 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
532 toggleThirdPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
533 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
534 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
535 } else { //Do not display the additional icons.
536 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
537 toggleThirdPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
538 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
539 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
546 public boolean onPrepareOptionsMenu(Menu menu) {
547 // Only enable Third-Party Cookies if SDK >= 21 and First-Party Cookies are enabled.
548 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
549 if ((Build.VERSION.SDK_INT >= 21) && firstPartyCookiesEnabled) {
550 toggleThirdPartyCookies.setEnabled(true);
552 toggleThirdPartyCookies.setEnabled(false);
555 // Enable DOM Storage if JavaScript is enabled.
556 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
557 toggleDomStorage.setEnabled(javaScriptEnabled);
559 // Enable Clear Cookies if there are any.
560 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
561 clearCookies.setEnabled(cookieManager.hasCookies());
563 // Enable Clear Form Data is there is any.
564 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
565 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
566 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
568 // Initialize font size variables.
569 int fontSize = mainWebView.getSettings().getTextZoom();
570 String fontSizeTitle;
571 MenuItem selectedFontSizeMenuItem;
573 // Prepare the font size title and current size menu item.
576 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
577 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
581 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
582 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
586 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
587 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
591 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
592 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
596 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
597 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
601 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
602 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
606 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
607 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
611 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
612 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
616 // Set the font size title and select the current size menu item.
617 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
618 fontSizeMenuItem.setTitle(fontSizeTitle);
619 selectedFontSizeMenuItem.setChecked(true);
621 // Only show `Refresh` if `swipeToRefresh` is disabled.
622 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
623 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
625 // Run all the other default commands.
626 super.onPrepareOptionsMenu(menu);
628 // `return true` displays the menu.
633 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
634 @SuppressLint("SetJavaScriptEnabled")
635 // removeAllCookies is deprecated, but it is required for API < 21.
636 @SuppressWarnings("deprecation")
637 public boolean onOptionsItemSelected(MenuItem menuItem) {
638 int menuItemId = menuItem.getItemId();
640 // Set the commands that relate to the menu entries.
641 switch (menuItemId) {
642 case R.id.toggleJavaScript:
643 // Switch the status of javaScriptEnabled.
644 javaScriptEnabled = !javaScriptEnabled;
646 // Apply the new JavaScript status.
647 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
649 // Update the privacy icon.
650 updatePrivacyIcons(privacyBrowserActivity);
652 // Display a `Snackbar`.
653 if (javaScriptEnabled) {
654 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
656 if (firstPartyCookiesEnabled) {
657 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
659 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
663 // Reload the WebView.
664 mainWebView.reload();
667 case R.id.toggleFirstPartyCookies:
668 // Switch the status of firstPartyCookiesEnabled.
669 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
671 // Update the menu checkbox.
672 menuItem.setChecked(firstPartyCookiesEnabled);
674 // Apply the new cookie status.
675 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
677 // Update the privacy icon.
678 updatePrivacyIcons(privacyBrowserActivity);
680 // Display a `Snackbar`.
681 if (firstPartyCookiesEnabled) {
682 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
684 if (javaScriptEnabled) {
685 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
687 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
691 // Reload the WebView.
692 mainWebView.reload();
695 case R.id.toggleThirdPartyCookies:
696 if (Build.VERSION.SDK_INT >= 21) {
697 // Switch the status of thirdPartyCookiesEnabled.
698 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
700 // Update the menu checkbox.
701 menuItem.setChecked(thirdPartyCookiesEnabled);
703 // Apply the new cookie status.
704 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
706 // Display a `Snackbar`.
707 if (thirdPartyCookiesEnabled) {
708 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
710 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
713 // Reload the WebView.
714 mainWebView.reload();
715 } // Else do nothing because SDK < 21.
718 case R.id.toggleDomStorage:
719 // Switch the status of domStorageEnabled.
720 domStorageEnabled = !domStorageEnabled;
722 // Update the menu checkbox.
723 menuItem.setChecked(domStorageEnabled);
725 // Apply the new DOM Storage status.
726 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
728 // Display a `Snackbar`.
729 if (domStorageEnabled) {
730 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
732 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
735 // Reload the WebView.
736 mainWebView.reload();
739 case R.id.toggleSaveFormData:
740 // Switch the status of saveFormDataEnabled.
741 saveFormDataEnabled = !saveFormDataEnabled;
743 // Update the menu checkbox.
744 menuItem.setChecked(saveFormDataEnabled);
746 // Apply the new form data status.
747 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
749 // Display a `Snackbar`.
750 if (saveFormDataEnabled) {
751 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
753 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
756 // Reload the WebView.
757 mainWebView.reload();
760 case R.id.clearCookies:
761 if (Build.VERSION.SDK_INT < 21) {
762 cookieManager.removeAllCookie();
764 cookieManager.removeAllCookies(null);
766 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
769 case R.id.clearDomStorage:
770 WebStorage webStorage = WebStorage.getInstance();
771 webStorage.deleteAllData();
772 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
775 case R.id.clearFormData:
776 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
777 mainWebViewDatabase.clearFormData();
778 mainWebView.reload();
781 case R.id.fontSizeFiftyPercent:
782 mainWebView.getSettings().setTextZoom(50);
785 case R.id.fontSizeSeventyFivePercent:
786 mainWebView.getSettings().setTextZoom(75);
789 case R.id.fontSizeOneHundredPercent:
790 mainWebView.getSettings().setTextZoom(100);
793 case R.id.fontSizeOneHundredTwentyFivePercent:
794 mainWebView.getSettings().setTextZoom(125);
797 case R.id.fontSizeOneHundredFiftyPercent:
798 mainWebView.getSettings().setTextZoom(150);
801 case R.id.fontSizeOneHundredSeventyFivePercent:
802 mainWebView.getSettings().setTextZoom(175);
805 case R.id.fontSizeTwoHundredPercent:
806 mainWebView.getSettings().setTextZoom(200);
810 Intent shareIntent = new Intent();
811 shareIntent.setAction(Intent.ACTION_SEND);
812 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
813 shareIntent.setType("text/plain");
814 startActivity(Intent.createChooser(shareIntent, "Share URL"));
817 case R.id.addToHomescreen:
818 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `@string/create_shortcut`.
819 DialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
820 createHomeScreenShortcutDialogFragment.show(getFragmentManager(), getResources().getString(R.string.create_shortcut));
822 //Everything else will be handled by `CreateHomeScreenShortcut` and the associated listener below.
826 mainWebView.reload();
830 // Don't consume the event.
831 return super.onOptionsItemSelected(menuItem);
836 // removeAllCookies is deprecated, but it is required for API < 21.
837 @SuppressWarnings("deprecation")
838 public boolean onNavigationItemSelected(MenuItem menuItem) {
839 int menuItemId = menuItem.getItemId();
841 switch (menuItemId) {
843 mainWebView.loadUrl(homepage, customHeaders);
847 if (mainWebView.canGoBack()) {
848 mainWebView.goBack();
853 if (mainWebView.canGoForward()) {
854 mainWebView.goForward();
859 // Launch BookmarksActivity.
860 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
861 startActivity(bookmarksIntent);
865 // Launch the system Download Manager.
866 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
868 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
869 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
871 startActivity(downloadManagerIntent);
875 // Launch `SettingsActivity`.
876 Intent settingsIntent = new Intent(this, SettingsActivity.class);
877 startActivity(settingsIntent);
881 // Launch `GuideActivity`.
882 Intent guideIntent = new Intent(this, GuideActivity.class);
883 startActivity(guideIntent);
887 // Launch `AboutActivity`.
888 Intent aboutIntent = new Intent(this, AboutActivity.class);
889 startActivity(aboutIntent);
892 case R.id.clearAndExit:
893 // Clear cookies. The commands changed slightly in API 21.
894 if (Build.VERSION.SDK_INT >= 21) {
895 cookieManager.removeAllCookies(null);
897 cookieManager.removeAllCookie();
900 // Clear DOM storage.
901 WebStorage domStorage = WebStorage.getInstance();
902 domStorage.deleteAllData();
905 WebViewDatabase formData = WebViewDatabase.getInstance(this);
906 formData.clearFormData();
908 // Clear cache. The argument of "true" includes disk files.
909 mainWebView.clearCache(true);
911 // Clear the back/forward history.
912 mainWebView.clearHistory();
914 // Clear any SSL certificate preferences.
915 MainWebViewActivity.mainWebView.clearSslPreferences();
917 // Clear `formattedUrlString`.
918 formattedUrlString = null;
920 // Clear `customHeaders`.
921 customHeaders.clear();
923 // Destroy the internal state of the webview.
924 mainWebView.destroy();
926 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
927 if (Build.VERSION.SDK_INT >= 21) {
928 finishAndRemoveTask();
938 // Close the navigation drawer.
939 drawerLayout.closeDrawer(GravityCompat.START);
944 public void onPostCreate(Bundle savedInstanceState) {
945 super.onPostCreate(savedInstanceState);
947 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
948 drawerToggle.syncState();
952 public void onConfigurationChanged(Configuration newConfig) {
953 super.onConfigurationChanged(newConfig);
955 // Reload the ad if this is the free flavor.
956 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
958 // Reinitialize the adView variable, as the View will have been removed and re-added in the free flavor by BannerAd.reloadAfterRotate().
959 adView = findViewById(R.id.adView);
961 // `invalidateOptionsMenu` should recalculate the number of action buttons from the menu to display on the app bar, but it doesn't because of the this bug: https://code.google.com/p/android/issues/detail?id=20493#c8
962 invalidateOptionsMenu();
966 public void onCreateHomeScreenShortcut(DialogFragment dialogFragment) {
967 // Get shortcutNameEditText from the alert dialog.
968 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
970 // Create the bookmark shortcut based on formattedUrlString.
971 Intent bookmarkShortcut = new Intent();
972 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
973 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
975 // Place the bookmark shortcut on the home screen.
976 Intent placeBookmarkShortcut = new Intent();
977 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
978 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
979 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
980 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
981 sendBroadcast(placeBookmarkShortcut);
985 public void onDownloadFile(DialogFragment dialogFragment, String downloadUrl) {
986 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
987 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
989 // Get the file name from `dialogFragment`.
990 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
991 String fileName = downloadFileNameEditText.getText().toString();
993 // Set the download save in the the `DIRECTORY_DOWNLOADS`using `fileName`.
994 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
995 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
997 // Allow `MediaScanner` to index the download if it is a media file.
998 downloadRequest.allowScanningByMediaScanner();
1000 // Add the URL as the description for the download.
1001 downloadRequest.setDescription(downloadUrl);
1003 // Show the download notification after the download is completed.
1004 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1006 // Initiate the download and display a Snackbar.
1007 downloadManager.enqueue(downloadRequest);
1010 public void viewSslCertificate(View view) {
1011 // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1012 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
1013 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1017 public void onSslErrorCancel() {
1018 sslErrorHandler.cancel();
1022 public void onSslErrorProceed() {
1023 sslErrorHandler.proceed();
1026 // Override onBackPressed to handle the navigation drawer and mainWebView.
1028 public void onBackPressed() {
1029 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
1031 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1032 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1033 drawerLayout.closeDrawer(GravityCompat.START);
1035 // Load the previous URL if available.
1036 assert mainWebView != null; //This assert removes the incorrect warning in Android Studio on the following line that mainWebView might be null.
1037 if (mainWebView.canGoBack()) {
1038 mainWebView.goBack();
1040 // Pass onBackPressed to the system.
1041 super.onBackPressed();
1047 public void onPause() {
1048 // We need to pause the adView or it will continue to consume resources in the background on the free flavor.
1049 BannerAd.pauseAd(adView);
1055 public void onResume() {
1058 // We need to resume the adView for the free flavor.
1059 BannerAd.resumeAd(adView);
1062 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1063 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
1064 String unformattedUrlString = urlTextBox.getText().toString().trim();
1066 URL unformattedUrl = null;
1067 Uri.Builder formattedUri = new Uri.Builder();
1069 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
1070 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1071 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
1072 if (!unformattedUrlString.startsWith("http")) {
1073 unformattedUrlString = "http://" + unformattedUrlString;
1076 // 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.
1078 unformattedUrl = new URL(unformattedUrlString);
1079 } catch (MalformedURLException e) {
1080 e.printStackTrace();
1083 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1084 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1085 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1086 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1087 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1088 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1090 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1091 formattedUrlString = formattedUri.build().toString();
1093 // Sanitize the search input and convert it to a DuckDuckGo search.
1094 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1096 // Use the correct search URL based on javaScriptEnabled.
1097 if (javaScriptEnabled) {
1098 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1099 } else { // JavaScript is disabled.
1100 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1104 mainWebView.loadUrl(formattedUrlString, customHeaders);
1106 // Hides the keyboard so we can see the webpage.
1107 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
1108 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1111 public static void updatePrivacyIcons(Activity activity) {
1112 // Get handles for the icons.
1113 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
1114 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
1115 MenuItem thirdPartyCookiesIcon = mainMenu.findItem(R.id.toggleThirdPartyCookies);
1116 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
1117 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
1119 // Update `privacyIcon`.
1120 if (javaScriptEnabled) {
1121 // `JavaScript` is enabled.
1122 privacyIcon.setIcon(R.drawable.javascript_enabled);
1124 if (firstPartyCookiesEnabled) {
1125 // `JavaScript` is disabled but cookies are enabled.
1126 privacyIcon.setIcon(R.drawable.warning);
1128 // All the dangerous features are disabled.
1129 privacyIcon.setIcon(R.drawable.privacy_mode);
1133 // Update `firstPartyCookiesIcon`.
1134 if (firstPartyCookiesEnabled) {
1135 // First-party cookies are enabled.
1136 firstPartyCookiesIcon.setIcon(R.drawable.cookies_warning);
1138 // First-party cookies are disabled.
1139 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1142 // Update `thirdPartyCookiesIcon`.
1143 if (firstPartyCookiesEnabled) {
1144 if (thirdPartyCookiesEnabled) {
1145 // Third-party cookies are enabled. Bad!
1146 thirdPartyCookiesIcon.setIcon(R.drawable.cookies_critical);
1148 // Third-party cookies are disabled.
1149 thirdPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1152 // First-party cookies are disabled, so third-party cookies are ghosted.
1153 thirdPartyCookiesIcon.setIcon(R.drawable.cookies_ghosted);
1156 // Update `domStorageIcon`.
1157 if (javaScriptEnabled) {
1158 if (domStorageEnabled) {
1159 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
1161 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
1164 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
1167 // Update `formDataIcon`.
1168 if (saveFormDataEnabled) {
1169 formDataIcon.setIcon(R.drawable.form_data_enabled);
1171 formDataIcon.setIcon(R.drawable.form_data_disabled);
1174 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
1175 ActivityCompat.invalidateOptionsMenu(activity);