Notice: Due to an ongoing migration of our storage and publishing system, material requested since last month will not be uploaded for the time being, and new requests are paused. All existing notes remain available.
The loadUrl() method is the standard function used to instruct a WebView instance to fetch and display the content from a given web address.
Question 3 of 60 · Building and Managing Web Apps in WebView · Easy
What permission must be added to the AndroidManifest.xml file for a WebView to access the internet?
Not quite. Try another option.
Answer: android.permission.INTERNET
To allow your app, including its WebView components, to connect to the internet, you must declare the INTERNET permission in your app's manifest file.
Question 4 of 60 · Building and Managing Web Apps in WebView · Easy
By default, what happens when a user clicks a link inside a WebView?
Not quite. Try another option.
Answer: The default web browser app opens to handle the link.
By default, WebView delegates URL handling to the system. To override this and keep navigation within your app, you must provide a WebViewClient.
Question 5 of 60 · Advance android programming · Easy
How do you enable JavaScript execution within a WebView?
Not quite. Try another option.
Answer: By calling webView.getSettings().setJavaScriptEnabled(true);
For security reasons, JavaScript is disabled by default in WebView. You must explicitly enable it through the WebSettings object associated with your WebView.
Question 6 of 60 · Supporting Different Screens in web Apps · Easy
Which HTML meta tag is essential for creating responsive web pages that adapt to different screen sizes within a WebView?
Not quite. Try another option.
Answer: <meta name="viewport" ... >
The viewport meta tag gives the browser instructions on how to control the page's dimensions and scaling, which is crucial for responsive design on mobile devices.
Question 7 of 60 · Supporting Different Screens in web Apps · Easy
What does width=device-width in the viewport meta tag signify?
Not quite. Try another option.
Answer: It sets the width of the page to follow the screen-width of the device.
The width=device-width part of the viewport meta tag tells the browser to match the page's width to the device's width in device-independent pixels.
Question 8 of 60 · Supporting Different Screens in web Apps · Easy
In CSS, which type of unit is recommended for font sizes to ensure they scale properly across different screen densities in a WebView?
Not quite. Try another option.
Answer: Relative units like em or rem
Relative units like em and rem allow font sizes to scale based on a parent element or the root element's font size, which is better for accessibility and responsiveness than fixed pixel sizes.
Question 9 of 60 · Migrating to WebView in Android · Easy
What is a major advantage of using a WebView to display certain content instead of building a fully native UI?
Not quite. Try another option.
Answer: Content can be updated on a web server without releasing a new app version.
Using WebView allows for dynamic content updates. You can change the web page on your server, and all users will see the new content immediately without needing to update the app from the app store.
Question 10 of 60 · Advance android programming · Easy
What is the purpose of the addJavascriptInterface() method in WebView?
Not quite. Try another option.
Answer: To allow JavaScript code in the WebView to call methods in your Android app's Java/Kotlin code.
This method creates a bridge, allowing the JavaScript running in the web page to interact with and invoke public methods of a supplied Java/Kotlin object.
Question 11 of 60 · Building and Managing Web Apps in WebView · Easy
Which class should you extend to handle events like page loading finished or URL navigation within your WebView?
Not quite. Try another option.
Answer: WebViewClient
WebViewClient is used for handling events related to rendering the content, such as page navigation, form submissions, and errors. It allows you to keep navigation within your WebView.
Question 12 of 60 · Migrating to WebView in Android · Easy
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?
Not quite. Try another option.
Answer: The terms can be updated on a server without an app update.
Legal documents like Terms of Service often change. Displaying them in a WebView loaded from a URL allows the business to update the terms on their website, and the app will automatically show the latest version.
Question 13 of 60 · Supporting Different Screens in web Apps · Easy
What is a common CSS technique used to apply different styles for different devices or screen sizes?
Not quite. Try another option.
Answer: Media Queries
CSS Media Queries allow you to apply specific styles based on device characteristics like its width, height, orientation, or resolution, which is the foundation of responsive web design.
Question 14 of 60 · Migrating to WebView in Android · Easy
What is a potential disadvantage of migrating a complex, interactive screen from native code to a WebView?
Not quite. Try another option.
Answer: Potential for slower performance and less smooth user experience.
While WebView is powerful, native components are generally more performant and offer a more fluid, platform-consistent user experience, especially for complex animations and interactions.
Question 15 of 60 · Advance android programming · Easy
What is the primary role of the WebChromeClient?
Not quite. Try another option.
Answer: To handle UI-related events like progress updates, JavaScript alerts, and favicons.
WebChromeClient is responsible for handling events that affect the browser UI (the 'chrome'), such as progress bar updates, JavaScript dialogs (alert, confirm), and receiving the page's title or icon.
Question 16 of 60 · Building and Managing Web Apps in WebView · Easy
How can you load locally stored HTML content from your app's assets folder into a WebView?
Not quite. Try another option.
Answer: Using the URL file:///android_asset/your_file.html
Android provides a special URL scheme, file:///android_asset/, to access files packaged within the app's assets directory directly from a WebView.
Question 17 of 60 · Migrating to WebView in Android · Easy
When considering migrating a feature to a WebView, what type of content is generally the best fit?
Not quite. Try another option.
Answer: Content that is primarily text and images, like articles or help pages.
Content that is document-centric and needs frequent updates without requiring deep integration with device hardware is an ideal candidate for a WebView-based approach.
Question 18 of 60 · Supporting Different Screens in web Apps · Easy
If a web page appears too zoomed out in a WebView on a high-density screen, which setting might be missing?
Not quite. Try another option.
Answer: The viewport meta tag with initial-scale=1.0
The initial-scale=1.0 part of the viewport tag sets the initial zoom level when the page is first loaded, ensuring a 1:1 relationship between CSS pixels and device-independent pixels.
Question 19 of 60 · Advance android programming · Easy
To navigate back through the history of a WebView, what method should you call?
Not quite. Try another option.
Answer: webView.goBack()
The goBack() method navigates to the previously visited page in the WebView's history, similar to the back button in a standard web browser.
Question 20 of 60 · Advance android programming · Easy
Before calling webView.goBack(), which method should you check to see if there is a page to go back to?
Not quite. Try another option.
Answer: webView.canGoBack()
The canGoBack() method returns a boolean value indicating whether the WebView has a back history. It's best practice to check this before calling goBack() to avoid unexpected behavior.
Question 21 of 60 · Building and Managing Web Apps in WebView · Medium
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?
Not quite. Try another option.
Answer: JavaScript is disabled by default for security reasons. You must enable it using webView.getSettings().setJavaScriptEnabled(true);.
For security purposes, JavaScript is disabled in a WebView by default to prevent potential cross-site scripting (XSS) attacks. To allow a web page to execute JavaScript, you must explicitly enable it via the WebSettings object.
Question 22 of 60 · Building and Managing Web Apps in WebView · Medium
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?
Not quite. Try another option.
Answer: Override shouldOverrideUrlLoading() in a custom WebViewClient.
By setting a custom WebViewClient and overriding the shouldOverrideUrlLoading() method, you can intercept all URL loading requests. Returning true from this method indicates that your app has handled the URL, preventing the WebView from taking its default action (like opening an external browser).
Question 23 of 60 · Supporting Different Screens in web Apps · Medium
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?
The viewport meta tag is crucial for responsive web design. width=device-width tells the browser to set the width of the page to the screen-width of the device, and initial-scale=1.0 sets the initial zoom level. This allows CSS media queries to work correctly.
Question 24 of 60 · Advance android programming · Medium
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?
Not quite. Try another option.
Answer: Annotate the method with @JavascriptInterface in a dedicated class and bind an instance of that class using webView.addJavascriptInterface().
The standard and secure mechanism for creating a bridge from JavaScript to native code is to use addJavascriptInterface(). Methods that you want to be accessible from JavaScript must be annotated with @JavascriptInterface to explicitly expose them, preventing unintended security vulnerabilities.
Question 25 of 60 · Building and Managing Web Apps in WebView · Medium
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?
Not quite. Try another option.
Answer: WebChromeClient and its onProgressChanged() method.
WebChromeClient is responsible for handling UI-related events like progress updates, JavaScript dialogs, and favicons. The onProgressChanged() callback provides the loading progress as an integer from 0 to 100, which is ideal for updating a ProgressBar.
Question 26 of 60 · Migrating to WebView in Android · Medium
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?
DOM Storage, which includes localStorage and sessionStorage, is disabled by default. To allow the web application to use these storage APIs and persist data, you must explicitly enable it with setDomStorageEnabled(true).
Question 27 of 60 · Supporting Different Screens in web Apps · Medium
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?
Not quite. Try another option.
Answer: setUseWideViewPort(true) and setLoadWithOverviewMode(true)
setUseWideViewPort(true) allows the WebView to use a viewport wider than the device screen, and setLoadWithOverviewMode(true) zooms out the content to fit the screen width upon initial load. Together, they provide a good overview of desktop-centric sites.
Question 28 of 60 · Advance android programming · Medium
How can you programmatically execute a JavaScript function from your native Android code and asynchronously receive its string result?
Not quite. Try another option.
Answer: Using webView.evaluateJavascript("myFunction();", callback).
The evaluateJavascript() method is the modern and preferred way to execute JavaScript and get a result back. It runs the script asynchronously and delivers the result of the execution to the provided ValueCallback, avoiding the performance and security issues of the older loadUrl("javascript:...") method.
Question 29 of 60 · Building and Managing Web Apps in WebView · Medium
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?
Not quite. Try another option.
Answer: In the onBackPressed() method of the host Activity.
The correct place to handle this is in the Activity's onBackPressed() callback. You should check if (webView.canGoBack()), and if it returns true, call webView.goBack(). Otherwise, you call super.onBackPressed() to allow the default back button behavior (like exiting the app).
Question 30 of 60 · Migrating to WebView in Android · Medium
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?
Not quite. Try another option.
Answer: A custom WebChromeClient that overrides the onShowFileChooser() method.
The native file chooser is not automatically triggered by a WebView. To handle file uploads, you must provide a custom WebChromeClient and implement the onShowFileChooser() method. Inside this method, you create and launch an Intent (e.g., Intent.ACTION_GET_CONTENT) to open the system file picker.
Question 31 of 60 · Supporting Different Screens in web Apps · Medium
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?
Not quite. Try another option.
Answer: Use responsive images with the <picture> element or the srcset attribute to provide multiple image resolutions.
Just as with standard web development, the best practice is to use responsive image techniques. The srcset attribute on <img> tags allows the browser (and WebView) to select the most appropriate image file based on the device's pixel density, ensuring sharpness without wasting bandwidth on unnecessarily large files.
Question 32 of 60 · Advance android programming · Medium
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?
Not quite. Try another option.
Answer: Call webView.clearCache(true), webView.clearHistory(), and CookieManager.getInstance().removeAllCookies(null).
A complete data wipe requires multiple steps. clearCache(true) clears the resource cache, clearHistory() clears the back/forward list, and CookieManager.getInstance().removeAllCookies() is essential for clearing session cookies. A single method does not cover all data types.
Question 33 of 60 · Building and Managing Web Apps in WebView · Medium
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?
Not quite. Try another option.
Answer: android:hardwareAccelerated="true"
Enabling hardware acceleration for the Activity allows the WebView to use the GPU for rendering operations. This significantly improves performance for graphically intensive content like CSS animations, transforms, and WebGL. It is enabled by default for modern target SDKs but is critical to ensure is active.
Question 34 of 60 · Migrating to WebView in Android · Medium
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?
Not quite. Try another option.
Answer: The WebView on older Android versions is based on an older version of the Chromium engine which does not support modern JavaScript syntax.
Android's WebView component is tied to the version of Chromium shipped with the OS. On older Android versions, this Chromium version can be significantly outdated and lack support for modern JavaScript and CSS features. To fix this, developers often use transpilers like Babel to convert modern code to a more compatible version (ES5).
Question 35 of 60 · Supporting Different Screens in web Apps · Medium
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?
The device-pixel-ratio media feature allows you to apply specific CSS rules for high-density (Retina) screens. A value of 2 targets devices like XHDPI, while 3 targets XXHDPI, enabling you to serve higher-resolution assets or adjust typography for clarity on these displays.
Question 36 of 60 · Advance android programming · Medium
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?
Not quite. Try another option.
Answer: setJavaScriptEnabled() and setAllowFileAccess()
The two most significant security risks in a WebView come from executing malicious scripts and allowing those scripts to access the local file system. Disabling JavaScript (setJavaScriptEnabled(false)) prevents script execution, and disabling file access (setAllowFileAccess(false)) prevents scripts from accessing local file:/// URLs, providing a much more secure environment for untrusted content.
Question 37 of 60 · Building and Managing Web Apps in WebView · Medium
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?
Not quite. Try another option.
Answer: Set webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW).
Android's WebView provides fine-grained control over mixed content (HTTP content on an HTTPS page). The setMixedContentMode() setting allows you to specify the policy, with MIXED_CONTENT_ALWAYS_ALLOW being the most permissive option. However, for security, the recommended approach is to fix the web content to use HTTPS for all resources.
Question 38 of 60 · Advance android programming · Medium
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?
The shouldInterceptRequest callback allows you to intercept any resource request (images, scripts, etc.) made by the WebView. You can inspect the request and return a custom WebResourceResponse with your own data, allowing for powerful features like custom caching, ad blocking, or modifying responses on the fly.
Question 39 of 60 · Migrating to WebView in Android · Medium
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?
Not quite. Try another option.
Answer: WebChromeClient and override onJsAlert().
WebChromeClient handles interactions with browser UI elements. By overriding onJsAlert(), you can intercept the JavaScript alert() call, prevent the default dialog from appearing, and show a native Android AlertDialog instead for a more integrated user experience. Returning true indicates you have handled the event.
Question 40 of 60 · Supporting Different Screens in web Apps · Medium
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?
Not quite. Try another option.
Answer: adjustPan
adjustResize is the default behavior, where the activity's main window is resized to make room for the soft keyboard. This changes the WebView's height and can disrupt layouts using vh units. adjustPan avoids resizing; instead, the contents of the window are panned to ensure the current focus is visible, preserving the WebView's original dimensions.
Question 41 of 60 · Building and Managing Web Apps in WebView · Hard
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?
Not quite. Try another option.
Answer: Use evaluateJavascript() with a ValueCallback and immediately dispatch the processing of the result to a background thread pool from within the onReceiveValue method.
The ValueCallback's onReceiveValue is guaranteed to be called on the main thread. The correct pattern is to receive the result on the main thread and then immediately hand off the heavy processing to a background thread (e.g., using a coroutine, RxJava, or an Executor) to prevent blocking the UI. The other options are either incorrect (hidden APIs are not reliable) or less direct for this specific problem.
Question 42 of 60 · Advance android programming · Hard
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?
Not quite. Try another option.
Answer: The method must return a WebResourceResponse synchronously. The correct way is to use a CountDownLatch to block the WebView's internal thread until the background operation completes.
shouldInterceptRequest is called on a background thread, but it must return a WebResourceResponse synchronously for the given request. If you need to perform an asynchronous operation (like another network call or a complex DB query) to get the data, you must block the current thread until the result is ready. Using a synchronization aid like CountDownLatch or CompletableFuture.get() is a common pattern to solve this.
Question 43 of 60 · Supporting Different Screens in web Apps · Hard
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?
Not quite. Try another option.
Answer: Use 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.
There is no automatic mechanism for WebView to pass window insets to CSS. The correct, advanced approach is to listen for insets on the native WebView View, extract the relevant values (e.g., from DisplayCutout), and then use JavaScript injection to set CSS custom properties (variables) on the <html> or <body> element. The web content's CSS can then use these variables with var(--safe-area-inset-top).
Question 44 of 60 · Migrating to WebView in Android · Hard
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?
Not quite. Try another option.
Answer: Implement shouldInterceptRequest, proxy every request through OkHttp, and let the existing Authenticator handle 401 responses. This requires complex synchronous handling of the async OkHttp call.
The most robust and seamless way to integrate advanced native networking logic (like an OkHttp Authenticator) is to intercept all WebView requests via shouldInterceptRequest. Inside this method, you create and execute an equivalent OkHttp Request, which will trigger your Authenticator on a 401. You then synchronously wait for the result and convert the OkHttp Response into a WebResourceResponse for the WebView. This transparently adds native capabilities to the WebView's networking.
Question 45 of 60 · Building and Managing Web Apps in WebView · Hard
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?
Not quite. Try another option.
Answer: In onDestroyView(), check if webView.parent is not null, cast it to ViewGroup and call removeView(webView), then call webView.destroy().
WebView can hold a strong reference to its Context. To properly clean it up, you must first detach it from its parent View, which breaks the View hierarchy's reference chain. Only after detaching it should you call destroy() to clean up its internal state. Performing this in onDestroyView ensures it happens when the Fragment's view is being torn down.
Question 46 of 60 · Advance android programming · Hard
What is a key security implication of Android's multi-process WebView (active by default on Android O+) regarding the @JavascriptInterface?
Not quite. Try another option.
Answer: Communication between the app process and the sandboxed renderer process is via IPC (Binder). Complex objects passed through the interface may be serialized, potentially leading to performance overhead or TransactionTooLargeException.
With multi-process WebView, the renderer runs in a separate, sandboxed process. When JavaScript calls a native method via the JS Bridge, the arguments and return values must be marshalled and sent over an IPC (Binder) transaction. This means large data transfers can be slow or even fail with a TransactionTooLargeException, a problem that does not exist with the older, in-process WebView.
Question 47 of 60 · Supporting Different Screens in web Apps · Hard
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?
Not quite. Try another option.
Answer: The <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.
The HTML <meta name="viewport"> tag is the standard way for a web page to declare its desired viewport properties. Modern WebView implementations prioritize the page's own viewport tag over the native WebSettings. setUseWideViewPort(true) is primarily a fallback for sites that do not have a viewport tag, forcing them to render in a larger viewport instead of a tiny one.
Question 48 of 60 · Building and Managing Web Apps in WebView · Hard
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?
Not quite. Try another option.
Answer: You must nullify the ValueCallback<Uri[]> member variable in onActivityResult if the result code is not Activity.RESULT_OK to prevent a stale callback from being used later.
The ValueCallback provided in onShowFileChooser is the mechanism to return the selected file URI(s) back to the WebView. If you store this callback but the user cancels the operation, you must call mUploadMessage.onReceiveValue(null) and then set mUploadMessage = null. Failure to do so can leave the WebView in a state where it's waiting for a callback that will never arrive, effectively breaking all subsequent file upload attempts.
Question 49 of 60 · Advance android programming · Hard
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?
Not quite. Try another option.
Answer: Remove the unresponsive WebView from the view hierarchy, destroy it, create a new WebView instance, add it back to the hierarchy, and reload the last known URL.
When the renderer process becomes unresponsive or is gone (onRenderProcessGone), the WebView instance becomes invalid and cannot be recovered by simple actions like reload(). The only robust recovery path is to completely destroy the faulty WebView object, create a fresh instance, configure it, add it to your layout, and then attempt to restore its state by loading the previous URL.
Question 50 of 60 · Migrating to WebView in Android · Hard
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?
Not quite. Try another option.
Answer: In the 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(); }.
The modern, recommended approach for handling back-press is using OnBackPressedDispatcher. The correct pattern is to add a custom callback. Inside the callback, you consume the back press for the WebView's internal navigation (webView.goBack()). If the WebView has no history, you must disable your callback and re-trigger the dispatcher's default behavior so the Activity or Fragment can be popped from the back stack. The deprecated onBackPressed() method should be avoided.
Question 51 of 60 · Building and Managing Web Apps in WebView · Hard
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?
Not quite. Try another option.
Answer: None. WebViewClient callbacks like shouldInterceptRequest are bypassed for requests handled by a registered Service Worker. You must use the ServiceWorkerController and ServiceWorkerClient classes.
The Service Worker API operates at a lower level than the WebViewClient. When a Service Worker's fetch event handler intercepts a network request, it is handled before WebViewClient.shouldInterceptRequest is ever triggered. To gain control at this level, you must use the dedicated Service Worker APIs, specifically by setting a ServiceWorkerClient via ServiceWorkerController.getInstance().setServiceWorkerClient().
Question 52 of 60 · Advance android programming · Hard
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?
Not quite. Try another option.
Answer: The frequent serialization/deserialization and IPC overhead between the renderer process and the app process for large strings is causing contention. A better approach would be to use WebView.postWebMessage with WebMessagePort for more efficient, dedicated communication.
While the JS bridge is convenient, it's not designed for high-throughput, large data transfers, especially with multi-process WebView. The WebMessagePort API is specifically designed for this use case. It creates a dedicated message channel between JavaScript and native code, which is more performant for frequent or large messages than the general-purpose JS bridge, as it can reduce IPC overhead.
Question 53 of 60 · Supporting Different Screens in web Apps · Hard
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?
Not quite. Try another option.
Answer: In Android, get the display density via 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.
Android's density (displayMetrics.density) is equivalent to the web's window.devicePixelRatio. A 1px CSS unit is scaled by this ratio to determine the number of physical pixels. To render a line that is only one physical pixel wide, you must define its CSS width to be 1 / devicePixelRatio CSS pixels. The most reliable way to get the exact device density is from the native side and provide it to the JavaScript context.
Question 54 of 60 · Building and Managing Web Apps in WebView · Hard
What is the fundamental difference in purpose between WebViewClient.onPageCommitVisible() and WebChromeClient.onProgressChanged()?
Not quite. Try another option.
Answer: 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.
onProgressChanged provides a rough percentage of the page load progress, useful for a progress bar. However, onPageCommitVisible is a much more precise signal. It fires at the moment the WebView has parsed enough of the HTML to perform its first paint, meaning the user can actually see content. This is a critical metric for perceived performance, occurring after onPageStarted but often well before onPageFinished.
Question 55 of 60 · Advance android programming · Hard
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?
Not quite. Try another option.
Answer: Implement WebViewClient.onReceivedClientCertRequest and in your implementation, call handler.proceed(privateKey, certificateChain) with the appropriate certificate from your app's KeyStore.
The Android WebView provides a specific callback, onReceivedClientCertRequest, designed for this exact purpose. When the web server requests a client certificate, this method is invoked on your WebViewClient. Your code is then responsible for retrieving the appropriate PrivateKey and certificate chain (e.g., from an app-specific KeyStore) and passing them to the ClientCertRequest handler to proceed with the TLS handshake.
Question 56 of 60 · Migrating to WebView in Android · Hard
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?
Not quite. Try another option.
Answer: Native -> JS: Use evaluateJavascript. JS -> Native: Use a @JavascriptInterface callback. This provides a direct, event-driven communication channel in both directions.
This approach is the most efficient. evaluateJavascript is the modern, asynchronous way to call into JS. The JS Bridge (@JavascriptInterface) allows JavaScript to directly invoke native methods. Together, they create an event-driven, low-latency, two-way binding. Polling is inefficient and resource-intensive. Using document.title is a clever but outdated and hacky method that is less reliable and performant.
Question 57 of 60 · Building and Managing Web Apps in WebView · Hard
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?
Not quite. Try another option.
Answer: Generate a nonce (a random, one-time-use string) on the native side. When loading the 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.
Using a nonce is the modern, secure way to allow specific inline scripts while maintaining a strong CSP. The server (or in this case, the native host) generates a unique nonce for each page load and includes it in the CSP header. Only <script> tags that have the matching nonce attribute will be allowed to execute. This prevents arbitrary script injection while still giving the trusted native host control.
Question 58 of 60 · Supporting Different Screens in web Apps · Hard
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?
Not quite. Try another option.
Answer: Override the Activity's onMultiWindowModeChanged method. Inside it, call webView.evaluateJavascript("document.dispatchEvent(new CustomEvent('multiWindowChanged', { detail: { isInMultiWindow: true } }))") to inform the web app.
The native Android framework provides the specific onMultiWindowModeChanged callback for this state change. The most robust solution is to listen for this native event and then use the JavaScript bridge (evaluateJavascript) to dispatch a custom JavaScript event within the WebView. The web application's JavaScript can then listen for this specific event and apply layout changes accordingly.
Question 59 of 60 · Advance android programming · Hard
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?
Not quite. Try another option.
Answer: The 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).
This is a classic inter-process communication problem. The WebView manages its cookies within your app's process. The Android DownloadManager is a system service running in its own process. It has no knowledge of your WebView's session. Therefore, you must act as a bridge: get the necessary authentication cookie from the CookieManager and explicitly add it as a request header to the DownloadManager.Request you create.
Question 60 of 60 · Building and Managing Web Apps in WebView · Hard
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?
Not quite. Try another option.
Answer: You must call the static method 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.
For security reasons, remote WebView debugging is disabled by default. It requires two explicit opt-ins: first, the application itself must be debuggable (android:debuggable="true" in AndroidManifest.xml), and second, you must programmatically enable it for all WebViews in your app by calling WebView.setWebContentsDebuggingEnabled(true). This should only be done in debug builds, not in production releases.
That's unit 6
Answer a few questions and your score shows up here.
Nearly through. Did unit 6 of CSE227 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 6 of CSE227 save you a night before the exam?
Then you can help keep it free for the next batch. Ads cover part of the server bill;
the rest comes out of a student's own pocket: the domain, the storage, and keeping
the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason.
to try again.