Unit 6 - Practice Quiz
1 What is the primary Android View component used to display web pages directly inside an application?
2
Which method is called to load a specific URL into a WebView?
3
What permission must be added to the AndroidManifest.xml file for a WebView to access the internet?
4
By default, what happens when a user clicks a link inside a WebView?
5
How do you enable JavaScript execution within a WebView?
webView.enableJavaScript();
<uses-permission android:name="android.permission.JAVASCRIPT" /> to the manifest.
webView.getSettings().setJavaScriptEnabled(true);
6
Which HTML meta tag is essential for creating responsive web pages that adapt to different screen sizes within a WebView?
7
What does width=device-width in the viewport meta tag signify?
8
In CSS, which type of unit is recommended for font sizes to ensure they scale properly across different screen densities in a WebView?
pt (points)
em or rem
in (inches)
px (pixels)
9
What is a major advantage of using a WebView to display certain content instead of building a fully native UI?
10
What is the purpose of the addJavascriptInterface() method in WebView?
WebView to call methods in your Android app's Java/Kotlin code.
11
Which class should you extend to handle events like page loading finished or URL navigation within your WebView?
12
A business wants to migrate their 'Terms of Service' page from a native TextView to a WebView. What is the primary benefit of this change?
13 What is a common CSS technique used to apply different styles for different devices or screen sizes?
14
What is a potential disadvantage of migrating a complex, interactive screen from native code to a WebView?
15
What is the primary role of the WebChromeClient?
16
How can you load locally stored HTML content from your app's assets folder into a WebView?
http://localhost/assets/your_file.html
file:///android_asset/your_file.html
assets://your_file.html
17
When considering migrating a feature to a WebView, what type of content is generally the best fit?
18
If a web page appears too zoomed out in a WebView on a high-density screen, which setting might be missing?
initial-scale=1.0
INTERNET permission
WebChromeClient
WebViewClient
19
To navigate back through the history of a WebView, what method should you call?
20
Before calling webView.goBack(), which method should you check to see if there is a page to go back to?
21
An Android application uses a WebView to display a modern web application. By default, the web app's interactive JavaScript components are not working. What is the most likely reason and how do you fix it?
WebViewClient has not been set, so JavaScript cannot execute.
INTERNET permission is missing in AndroidManifest.xml.
webView.getSettings().setJavaScriptEnabled(true);.
22
You want to prevent a WebView from opening external links in the device's default browser, and instead handle all URL loading within the app itself. Which method should you override?
onJsAlert() in a custom WebChromeClient.
shouldOverrideUrlLoading() in a custom WebViewClient.
onLoadResource() in a custom WebViewClient.
webView.getSettings().setBlockNetworkLoads(true);.
23
A web page designed for desktops looks too wide and requires horizontal scrolling when loaded in a WebView on a mobile device. Which HTML meta tag is essential to add to the web page's <head> to make it adapt to the device's screen width?
24
What is the correct and secure way to expose a method from your Android Kotlin/Java code to be callable by JavaScript running inside a WebView?
@JavascriptInterface in a dedicated class and bind an instance of that class using webView.addJavascriptInterface().
webView.evaluateJavascript() to poll for changes from the web page.
WebChromeClient and override onJsPrompt() to handle messages from JavaScript.
25
A developer needs to display a progress bar that updates as a web page loads in a WebView. Which client and method are most appropriate for this task?
WebChromeClient and its onReceivedTitle() method.
WebViewClient and its onLoadResource() method.
WebChromeClient and its onProgressChanged() method.
WebViewClient and its onPageFinished() method.
26
You are migrating a web application that relies heavily on HTML5 localStorage to an Android app using WebView. After loading the app, you notice that data saved in localStorage does not persist between app sessions. Which WebSettings call is required to fix this?
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
27
To ensure a non-mobile-optimized webpage is initially zoomed out to fit the screen's width when loaded in a WebView, which pair of WebSettings methods should be set to true?
setBuiltInZoomControls(true) and setDisplayZoomControls(true)
setUseWideViewPort(true) and setLoadWithOverviewMode(true)
setSupportZoom(true) and setUseWideViewPort(true)
setLoadWithOverviewMode(true) and setJavaScriptEnabled(true)
28 How can you programmatically execute a JavaScript function from your native Android code and asynchronously receive its string result?
webView.evaluateJavascript("myFunction();", callback).
webView.postWebMessage().
onJsPrompt in WebChromeClient.
webView.loadUrl("javascript:myFunction();") and a @JavascriptInterface.
29
In your WebView-based app, you want the physical back button to navigate the WebView's history first, and only exit the app if there is no history to go back to. Where should this logic be implemented?
onKeyDown() method of the WebView itself.
shouldOverrideUrlLoading() method of the WebViewClient.
onBackPressed() method of the host Activity.
onBackPressed() method of the host Fragment.
30
A migrated web application includes a file upload feature using an <input type="file"> element. This feature does not work in the WebView. What must be implemented to support file selection?
READ_EXTERNAL_STORAGE permission in the AndroidManifest.xml.
setDomStorageEnabled(true).
WebViewClient that overrides shouldInterceptRequest().
WebChromeClient that overrides the onShowFileChooser() method.
31
To deliver the best quality images for a web app running in a WebView on high-density displays (e.g., XHDPI, XXHDPI), what is the recommended web development practice?
<picture> element or the srcset attribute to provide multiple image resolutions.
webView.setInitialScale(200) to force images to render larger.
32
A user logs out of your app, and you need to completely clear all data associated with the WebView, including cookies, cache, and local storage. Which of the following approaches is most effective?
webView.clearView() to reset the visual state.
WebView instance.
webView.clearCache(true), webView.clearHistory(), and CookieManager.getInstance().removeAllCookies(null).
webView.getSettings().setJavaScriptEnabled(false).
33
To improve WebView rendering performance, especially for pages with complex CSS animations and transitions, what setting should be enabled for the Activity hosting the WebView in AndroidManifest.xml?
android:hardwareAccelerated="true"
android:configChanges="orientation|screenSize"
android:largeHeap="true"
android:windowSoftInputMode="adjustResize"
34
A web app that works in modern desktop browsers uses cutting-edge JavaScript (ES2020) features. When loaded into a WebView on an older Android device (e.g., API 21), these features cause errors. What is the most likely reason?
INTERNET permission works differently on older Android versions.
WebView on older Android versions is based on an older version of the Chromium engine which does not support modern JavaScript syntax.
35
You are debugging a responsive layout in a WebView. What CSS media query is specifically used to target devices based on their screen's pixel density?
@media (-webkit-min-device-pixel-ratio: 2)
@media (orientation: landscape)
@media (prefers-color-scheme: dark)
@media (min-width: 480px)
36
To mitigate the risk of Cross-Site Scripting (XSS) when loading potentially untrusted third-party content in a WebView, which two WebSettings properties should be set to false unless absolutely necessary?
setUseWideViewPort() and setLoadWithOverviewMode()
setJavaScriptEnabled() and setAllowFileAccess()
setSupportZoom() and setBuiltInZoomControls()
setDomStorageEnabled() and setDatabaseEnabled()
37
Your WebView loads a page over HTTPS, but some resources on that page (like images or scripts) are loaded over HTTP. The WebView blocks this mixed content by default on newer Android versions. How can you change this behavior to allow mixed content?
webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW).
onReceivedSslError in WebViewClient and call handler.proceed().
android:usesCleartextTraffic="true" to the application tag in the manifest.
38
You need to intercept network requests made by a WebView to modify headers or provide a cached response from your app's native cache. Which WebViewClient method is designed for this purpose?
onPageFinished(WebView view, String url)
shouldInterceptRequest(WebView view, WebResourceRequest request)
shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse)
39
When converting a web app to a WebView-based Android app, you want to replace the standard browser alert() dialogs with native Android AlertDialogs. Which client and method must you implement?
WebChromeClient and override onJsPrompt().
WebViewClient and override onReceivedError().
WebChromeClient and override onJsAlert().
WebViewClient and override shouldOverrideUrlLoading().
40
A web app in a WebView uses CSS vh units (viewport height) for layout. When the Android soft keyboard appears, the WebView resizes, causing the layout to break. What windowSoftInputMode setting in AndroidManifest.xml for the Activity can help prevent this resizing behavior?
stateVisible
adjustPan
stateHidden
adjustResize
41
You are using WebView.evaluateJavascript() to invoke a JavaScript function that returns a large JSON object. To avoid performance issues on the main thread, you want to process the result on a background thread. Which of the following approaches is the most robust and correct for handling the asynchronous result off the main thread?
evaluateJavascript() call within a coroutine using suspendCancellableCoroutine and switch context to Dispatchers.IO before processing the result returned by the callback.
evaluateJavascript() with a ValueCallback and immediately dispatch the processing of the result to a background thread pool from within the onReceiveValue method.
ValueCallback for evaluateJavascript is always invoked on the main thread. A better approach is to use a @JavascriptInterface where the JavaScript calls a native method, which can then perform the work on a background thread.
WebView to run its JavaScript execution on a background thread using a hidden WebSettings API, so the ValueCallback is also executed on a background thread.
42
When implementing WebViewClient.shouldInterceptRequest(WebView view, WebResourceRequest request), you decide to replace the network call with a response from a local, encrypted database. To avoid blocking the UI thread, you perform the database query and decryption on a background thread. What is the primary challenge with this asynchronous approach and how is it correctly solved?
WebResourceResponse synchronously. The correct way is to use a CountDownLatch to block the WebView's internal thread until the background operation completes.
LOAD_CACHE_ELSE_NETWORK instead.
43 To ensure your web content respects the display cutout (notch) area on modern Android devices, you need to pass the safe area insets from the native layout to the web app's CSS. What is the most effective technique to achieve this?
View.setOnApplyWindowInsetsListener on the WebView, get the DisplayCutout insets, and then inject a <style> tag into the HTML <head> using evaluateJavascript() that sets CSS variables like --safe-area-inset-top.
webSettings.setSupportDisplayCutout(true) which automatically handles the insets.
WebView automatically handles display cutouts via the user-agent string, and the web content only needs to use the env(safe-area-inset-top) CSS function.
onConfigurationChanged, check for inset changes, and reload the entire WebView with a new URL parameter containing the inset values.
44
You are migrating a native login flow, which uses OkHttp with a custom Authenticator for automatic refresh token logic, to a WebView-based flow. How can you replicate the automatic token refresh functionality for network requests originating from the WebView?
CookieManager to set the refresh token as a cookie and rely on the server-side to handle the redirect to the refresh endpoint.
WebView's network stack is isolated and cannot be integrated with OkHttp's Authenticator mechanism.
shouldInterceptRequest, proxy every request through OkHttp, and let the existing Authenticator handle 401 responses. This requires complex synchronous handling of the async OkHttp call.
@JavascriptInterface method that the web app's fetch interceptor can call when it receives a 401. The native method handles the token refresh and returns the new token to the JavaScript.
45
Consider a WebView in a Fragment. Which of the following is the most robust method to prevent WebView-related memory leaks, especially concerning the Context?
onDestroyView(), check if webView.parent is not null, cast it to ViewGroup and call removeView(webView), then call webView.destroy().
onStop(), call webView.pauseTimers() and in onResume() call webView.resumeTimers().
WebView programmatically in onCreateView using applicationContext instead of the Activity context.
WebView reference to null in onDestroyView() is sufficient for the garbage collector.
46
What is a key security implication of Android's multi-process WebView (active by default on Android O+) regarding the @JavascriptInterface?
@JavascriptInterface object is cloned into the renderer process, leading to thread-safety issues if not designed to be stateless.
WebView disables @JavascriptInterface by default for security, and it cannot be re-enabled.
TransactionTooLargeException.
47
You have a web page with <meta name="viewport" content="width=device-width, initial-scale=1.0">. In your Android app, you set webView.settings.setUseWideViewPort(true) and webView.settings.setLoadWithOverviewMode(true). What will be the resulting behavior of the WebView's viewport?
<meta> tag will take precedence. The WebView will render the page with a viewport width equal to the device's width in CSS pixels, and the setUseWideViewPort settings will be effectively ignored.
WebView will first load the page in a wide viewport, and then the <meta> tag will trigger a re-layout to fit the device-width, causing a visible flash of content.
WebView will use a wide viewport (typically 980px), and then setLoadWithOverviewMode will zoom out to fit this wide viewport entirely on the screen, ignoring the <meta> tag.
WebView to fall back to a default behavior without a properly configured viewport.
48
You are implementing a custom WebChromeClient to handle file uploads from a <input type="file"> tag. Your implementation of onShowFileChooser correctly launches an Intent to pick a file. What is a critical, and often missed, step to ensure your implementation works correctly across all scenarios, including when the user cancels the file picker or the app is backgrounded?
ValueCallback.onReceiveValue(null) within the onShowFileChooser method before returning true.
WebView has the WRITE_EXTERNAL_STORAGE permission, even if you are only reading a file using the Storage Access Framework.
ValueCallback<Uri[]> member variable in onActivityResult if the result code is not Activity.RESULT_OK to prevent a stale callback from being used later.
onShowFileChooser method must be synchronized to prevent race conditions if the user clicks the input multiple times quickly.
49
You observe that your WebView crashes intermittently, and the WebViewRenderProcessClient.onRenderProcessUnresponsive callback is triggered. Your app needs to be extremely resilient. What is the best strategy to recover from this state?
onRenderProcessGone and show a sad face UI.
webView.reload() within the onRenderProcessUnresponsive callback to force the renderer to restart.
WebView from the view hierarchy, destroy it, create a new WebView instance, add it back to the hierarchy, and reload the last known URL.
50
You are migrating a native app screen to a WebView. The native screen had complex back-press logic managed by OnBackPressedDispatcher. How do you correctly integrate the WebView's own history stack (canGoBack()/goBack()) with the Activity's back-press handling?
WebView automatically integrates with the back-press dispatcher.
WebView subclass that overrides onKeyDown and handles KeyEvent.KEYCODE_BACK internally, calling goBack() if its history is not empty.
Activity's onCreate, add an OnBackPressedCallback to the OnBackPressedDispatcher. In the callback's handleOnBackPressed method, check if (webView.canGoBack()) { webView.goBack(); } else { setEnabled(false); activity.onBackPressed(); }.
Activity's onBackPressed (deprecated), check if (webView.canGoBack()) { webView.goBack(); } else { super.onBackPressed(); }.
51
Your WebView needs to load a page that uses Service Workers for offline caching. Which WebViewClient callback is most critical for debugging and managing the interaction between the WebView and the Service Worker, especially for intercepting network requests handled by the worker?
onPageFinished is the only callback that can reliably indicate if a Service Worker has been successfully registered and is controlling the page.
shouldInterceptRequest is still called, but the WebResourceRequest object will have a special flag indicating it was served from a Service Worker.
onLoadResource will be called for every resource, regardless of whether it came from the network, cache, or Service Worker.
WebViewClient callbacks like shouldInterceptRequest are bypassed for requests handled by a registered Service Worker. You must use the ServiceWorkerController and ServiceWorkerClient classes.
52
You are using a @JavascriptInterface to expose a native method postData(String json). This method is called frequently with large JSON payloads from JavaScript. You notice performance degradation. What is the most likely cause and the best optimization?
WebView.postWebMessage with WebMessagePort for more efficient, dedicated communication.
String object in Java is creating too much garbage collection pressure. You should use a StringBuilder in the interface method signature.
@JavascriptInterface runs on the UI thread, and processing large strings blocks it. The solution is to make the postData method synchronized.
53
To achieve a pixel-perfect layout where a 1px CSS border in your web content renders as exactly one physical pixel on a xxhdpi device (which has a density of 3.0), what calculation and communication between JavaScript and native code is required?
1dp as the unit in a stylesheet injected from the native side, as WebView understands dp units.
WebView if you set <meta name="viewport" content="width=device-width, initial-scale=1">.
transform: scale(1/density) on the container element.
context.resources.displayMetrics.density. Pass this value (e.g., 3.0) to JavaScript via a JS interface. JavaScript should then set the border width to (1.0 / window.devicePixelRatio) + 'px', which will be 0.333px.
54
What is the fundamental difference in purpose between WebViewClient.onPageCommitVisible() and WebChromeClient.onProgressChanged()?
onPageCommitVisible is called once when the content of the page becomes visible to the user, marking the end of the 'above-the-fold' render. onProgressChanged is called multiple times during the page load to report the percentage of resources loaded.
onPageCommitVisible is part of the newer WebViewClient API and is more reliable than waiting for onProgressChanged to reach 100.
onPageCommitVisible is called when the page is fully interactive (DOM ready and JavaScript loaded), while onProgressChanged reaching 100 means all subresources (images, scripts) have finished downloading.
onProgressChanged reports the network loading progress, while onPageCommitVisible reports the DOM parsing progress.
55
Your WebView must securely load content from a server that uses a client SSL certificate for authentication. How do you configure the WebView to provide this certificate during the TLS handshake?
WebView will automatically pick it up for the specified host.
webView.getSettings().setClientCertificate(pathToCert, password).
shouldInterceptRequest, proxy the request through a custom SSLSocketFactory (e.g., with OkHttp) that is configured with your KeyStore, and return the response.
WebViewClient.onReceivedClientCertRequest and in your implementation, call handler.proceed(privateKey, certificateChain) with the appropriate certificate from your app's KeyStore.
56
While migrating a feature to a WebView, you need to maintain two-way data synchronization between a native component (e.g., a SeekBar) and a JavaScript element in the WebView. Which of the following describes the most efficient and responsive implementation?
evaluateJavascript. JS -> Native: Use a @JavascriptInterface callback. This provides a direct, event-driven communication channel in both directions.
evaluateJavascript every 100ms to get the web value, and JavaScript calls the native interface every 100ms to get the native value.
fetch call in JavaScript can access.
webView.loadUrl("javascript:updateValue(...)"). JS -> Native: Have JavaScript change the document title (document.title = ...) and listen for it in WebChromeClient.onReceivedTitle().
57
You set a strict Content Security Policy (CSP) via HTTP headers for your web app. Now, you need to execute a specific, trusted script from your native Android code using evaluateJavascript. The CSP blocks inline scripts (script-src 'self'), causing the evaluation to fail. What is the correct way to allow this single execution without globally weakening your CSP?
webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW) which also bypasses certain CSP restrictions.
WebView, inject this nonce into the CSP header (script-src 'self' 'nonce-YOUR_NONCE'). Then, when calling evaluateJavascript, wrap your script in a <script nonce="YOUR_NONCE">...</script> tag and evaluate that.
'unsafe-inline'.
shouldInterceptRequest, manually download the HTML, remove the CSP header, and then use webView.loadDataWithBaseURL to load the modified content.
58
Your WebView displays content that needs to adapt when the user enters Android's split-screen mode. Standard CSS @media queries based on viewport width are not sufficient as the width might not change significantly, but the aspect ratio and available space do. How can the web content be reliably notified of the native app entering or exiting split-screen mode?
Activity's onMultiWindowModeChanged method. Inside it, call webView.evaluateJavascript("document.dispatchEvent(new CustomEvent('multiWindowChanged', { detail: { isInMultiWindow: true } }))") to inform the web app.
WebView's user-agent string is automatically updated with multi-window information, which JavaScript can parse.
59
When using setDownloadListener to manage file downloads with the system DownloadManager, a user reports that downloads are failing for URLs that require an authentication cookie. Why does this happen and what is the solution?
contentDisposition string. It must be parsed correctly to extract the filename before passing the request to the DownloadManager.
android.permission.PROCESS_OUTGOING_CALLS permission for the DownloadManager to share authentication state with the app.
DownloadManager runs in a separate system process and does not have access to the WebView's cookie store. You must manually retrieve the cookie for the URL using CookieManager.getInstance().getCookie(url) and add it as an HTTP header to the DownloadManager.Request using addRequestHeader("Cookie", cookieValue).
DownloadManager does not support authenticated downloads. You must implement the entire download logic manually using an HTTP client like OkHttp in a foreground Service.
60
You are debugging a complex web application in a WebView and suspect a race condition between multiple JavaScript files. You want to debug the JavaScript code using Chrome DevTools. Which statement about setting up remote debugging is most accurate?
<uses-permission android:name="android.permission.INTERNET"/> and android:usesCleartextTraffic="true" to the manifest to allow the debugging socket to connect.
WebView.setWebContentsDebuggingEnabled(true) and ensure your app's debuggable flag is true in the manifest. The device must then be connected via USB with debugging enabled to appear in chrome://inspect.
WebChromeClient and override onConsoleMessage to manually forward logs to Logcat, as direct inspection is not possible.
WebView instances. You just need to connect the device and open Chrome DevTools.