Skip to content

Android Native Layer (Java)

This page examines the Android implementation shipped by zikzak_inappwebview_android: a Java Android library that adapts Flutter platform views and method channels to Android WebView, Chrome Custom Tabs, headless WebViews, and process-wide WebView services. The focus is the native architecture an advanced contributor needs before modifying bridge behavior, lifecycle handling, security interception, or platform-view creation.

Sources: build.gradle, InAppWebViewFlutterPlugin.java

The Android native layer sits between the federated Dart platform implementation and the Android WebView runtime. AndroidInAppWebViewPlatform constructs Android controllers and widgets, while the Java plugin registers the platform-view factory and all native method-channel handlers. The native side therefore has two distinct object graphs: process-scoped managers for global services and per-instance WebViews for actual page content.

Sources: inappwebview_platform.dart, InAppWebViewFlutterPlugin.java

flowchart TD
A[Flutter Android Platform Interface] --> B[AndroidInAppWebViewPlatform]
B --> C[AndroidInAppWebViewWidget]
C --> D[FlutterWebViewFactory]
D --> E[FlutterWebView]
E --> F[InAppWebView]
F --> G[WebViewChannelDelegate]
F --> H[InAppWebViewClient / ChromeClient]
F --> I[JavaScriptBridgeInterface]
J[InAppWebViewFlutterPlugin] --> K[Process Managers]
J --> D
K --> L[Cookies / Proxy / Storage / Browser / Headless]

The important architectural distinction is that platform-view creation is not the same operation as WebView construction. The factory may reuse a kept-alive or headless instance, while the WebView constructor wires the per-instance channel and the prepare() method installs clients, settings, and deferred JavaScript infrastructure.

Sources: FlutterWebViewFactory.java, InAppWebView.java

InAppWebViewFlutterPlugin implements both FlutterPlugin and ActivityAware. Engine attachment stores the application context, binary messenger, assets, and nullable activity, then constructs the browser, headless, Custom Tabs, platform-view, cookie, storage, credential, service-worker, feature, proxy, print, tracing, and process-global managers. The activity may legitimately be absent at this point because engine attachment and activity attachment are ordered by the host lifecycle.

Sources: InAppWebViewFlutterPlugin.java

Native package Responsibility Representative type
webview Platform-view creation, per-view channel, WebView clients FlutterWebViewFactory, WebViewChannelDelegate
webview.in_app_webview Concrete WebView and composition/input behavior InAppWebView, InputAwareWebView
headless_in_app_webview Off-screen instances, LRU cap, readiness gate HeadlessInAppWebViewManager
in_app_browser and chrome_custom_tabs Activity-based browsing surfaces InAppBrowserManager
content_blocker Rule parsing and request-time matching ContentBlockerHandler
security URL, HTTPS, certificate, and response policy ZikZakSecurityManager
types and plugin_scripts_js Wire conversion and injected JavaScript UserContentController, JavaScriptBridgeJS

Sources: InAppWebViewFlutterPlugin.java, AndroidManifest.xml

Engine detachment disposes managers in reverse service order and removes activity lifecycle callbacks when the activity detaches. Configuration changes unregister and later re-register the Custom Tabs activity callbacks, which prevents stale activity references from surviving recreation.

Sources: InAppWebViewFlutterPlugin.java, InAppWebViewFlutterPlugin.java

FlutterWebViewFactory is registered under the view type wtf.zikzak/zikzak_inappwebview and receives creation parameters using StandardMessageCodec. Its create() method first looks for a running headless WebView identified by headlessWebViewId; if found, it detaches that native instance and transfers it into the platform view. Otherwise it may reuse a keepAliveId instance, removing the old parent before reattachment.

Sources: InAppWebViewFlutterPlugin.java, FlutterWebViewFactory.java

A reused instance skips the initial load. A newly constructed FlutterWebView is registered in the keep-alive map when applicable and receives makeInitialLoad(params) exactly once. This is the native mechanism that makes reattachment stateful rather than recreating a page from scratch.

Sources: FlutterWebViewFactory.java

FlutterWebView is a composition root rather than a WebView subclass. It parses initial settings and user scripts, creates InAppWebView, wraps it in PullToRefreshLayout, attaches a FindInteractionController, and returns the outer layout from getView(). This means the platform view’s visible root is normally the pull-to-refresh container, not the WebView itself.

Sources: FlutterWebView.java

Initial navigation is deliberately deferred with View.post() unless a window transport was wired. The post ensures JavaScript bridge registration precedes renderer page execution, including cached pages and sleeping-tab restoration. For windowId creation, the factory path consumes a parked WebViewTransport message and, when document-start scripts are supported, schedules prepareAndAddUserScripts() separately because Chromium does not reliably apply them to window-id-created WebViews.

Sources: FlutterWebView.java

The Dart widget supplies exactly the identifiers consumed by the factory: windowId, headlessWebViewId, and keepAliveId. Hybrid composition is selected from initialSettings.useHybridComposition, defaulting to true, and determines whether Flutter uses an expensive Android view surface or the virtual-display path.

Sources: in_app_webview.dart, in_app_webview.dart

Every InAppWebView creates a method channel named wtf.zikzak/zikzak_inappwebview_ plus the native object id. WebViewChannelDelegate installs itself as the handler and dispatches through the WebViewChannelDelegateMethods enum, which makes unknown methods fail explicitly with notImplemented() rather than silently falling through.

Sources: InAppWebView.java, WebViewChannelDelegate.java, WebViewChannelDelegateMethods.java

Channel Scope Native owner
wtf.zikzak/zikzak_inappwebview_manager Global WebView package, cache, debugging, keep-alive disposal InAppWebViewManager
wtf.zikzak/zikzak_inappwebview_<id> One inline or browser WebView WebViewChannelDelegate
wtf.zikzak/flutter_headless_inappwebview Headless creation, cap, disposal HeadlessInAppWebViewManager
wtf.zikzak/flutter_headless_inappwebview_<id> One headless instance’s size and lifecycle HeadlessWebViewChannelDelegate
wtf.zikzak/zikzak_inappbrowser Browser activity and system-browser launch InAppBrowserManager
wtf.zikzak/zikzak_inappwebview_cookiemanager Process cookie store MyCookieManager
wtf.zikzak/zikzak_inappwebview_proxycontroller Global proxy override ProxyManager

Sources: InAppWebViewManager.java, HeadlessInAppWebViewManager.java, MyCookieManager.java, ProxyManager.java

ChannelDelegateImpl centralizes handler installation and disposal: construction calls setMethodCallHandler(this), while disposal clears the handler and nulls the channel. Native events travel back through typed callback classes; asynchronous callbacks return through invokeMethod, and synchronous operations use Util.invokeMethodAndWaitResult where the Android API requires a blocking result.

Sources: ChannelDelegateImpl.java, WebViewChannelDelegate.java

InAppWebView extends InputAwareWebView, which extends Android WebView. Its constructor installs the per-instance channel before any page work begins. prepare() resumes global timers, installs InAppWebViewChromeClient, selects a WebViewClient implementation, optionally installs a render-process client, applies settings, and schedules bridge registration.

Sources: InAppWebView.java, InAppWebView.java

Client selection is version-sensitive. The implementation checks the current WebView package and Chromium major version; known Chromium WebView versions at or above 73 use InAppWebViewClientCompat, while other implementations fall back to InAppWebViewClient for compatibility with a documented Chromium defect.

Sources: InAppWebView.java

The base InAppWebViewClient is also a security interception point. Before normal navigation handling it validates URL safety, enforces HTTPS-only policy, optionally upgrades HTTP URLs, and only then invokes the configurable shouldOverrideUrlLoading behavior. Response processing can add security headers through ZikZakSecurityManager without replacing the original response on failure.

Sources: InAppWebViewClient.java, InAppWebViewClient.java, InAppWebViewClient.java

InAppWebViewChromeClient handles browser chrome concerns that are not part of page navigation: file chooser activity results, custom fullscreen views, JavaScript dialogs, geolocation prompts, and permission requests. It registers itself with the plugin activity binding and, for browser activities, with the browser’s activity-result listener collection.

Sources: InAppWebViewChromeClient.java

The Android bridge global is window.zikzak_inappwebview. Its injected callHandler function allocates a promise callback id, invokes the Java interface’s _callHandler, and stores resolve and reject on the global object. A cross-origin frame fallback forwards calls to window.top when the frame itself has no bridge object.

Sources: JavaScriptBridgeJS.java, JavaScriptBridgeJS.java

Registration is deferred inside prepare() with post(). The native code explicitly avoids calling addJavascriptInterface() and document-start script registration synchronously during platform-view creation because their renderer binder IPC can interfere with Flutter’s platform-view-created dispatch. Runtime exceptions are logged instead of escaping from the main looper.

Sources: InAppWebView.java

JavaScriptBridgeInterface._callHandler marshals work onto the WebView looper. Internal handlers such as print, async JavaScript evaluation, and content-world evaluation are resolved natively; all other handler names are forwarded to Dart through onCallJsHandler. The Dart result is converted back into JavaScript that resolves or rejects the stored promise and deletes its callback entry.

Sources: JavaScriptBridgeInterface.java, JavaScriptBridgeInterface.java

prepareAndAddUserScripts() registers the promise polyfill, bridge script, optional console and print scripts, focus/blur scripts, AJAX/fetch interception, resource-load reporting, and initial user scripts. UserContentController stores plugin and user scripts by injection time and uses AndroidX document-start script handlers when DOCUMENT_START_SCRIPT is available; failures are caught and logged because Chromium may not yet be ready during cold starts.

Sources: InAppWebView.java, UserContentController.java, UserContentController.java

For broader bridge semantics and handler naming rules, continue with The JavaScript Bridge Global and Handler Wiring.

Settings, Feature Gating, and Content Blockers

Section titled “Settings, Feature Gating, and Content Blockers”

Settings are represented twice: as a wire map and as InAppWebViewSettings. Initial values are applied during prepare(), while setSettings() compares old and new values and applies only changed capabilities. AndroidX feature checks, SDK checks, and defensive ClassCastException handling are pervasive because OEM WebView wrappers do not always honor standard WebSettings contracts.

Sources: InAppWebViewSettings.java, InAppWebView.java, InAppWebView.java

The content blocker model is a list of trigger/action pairs. ContentBlockerHandler.checkUrl() matches URL filters, resource types, domains, load type, and top-frame constraints. A block returns an empty WebResourceResponse; CSS actions inject display-hiding JavaScript; HTTPS actions can fetch and reconstruct the response from the upgraded URL.

Sources: ContentBlocker.java, ContentBlockerHandler.java, ContentBlockerHandler.java

HeadlessInAppWebViewManager owns a map of live headless instances and a last-used timestamp map. The default hard cap is three. Creation at the cap evicts the least-recently-used instance, not the oldest registration, because long-lived sessions are more likely to be active and native instances can outlive a Dart hot restart.

Sources: HeadlessInAppWebViewManager.java, HeadlessInAppWebViewManager.java

Each headless run constructs a FlutterWebView, wraps it in HeadlessInAppWebView, prepares its size, and attaches it to a dedicated off-screen container. The run() completion is gated by firstNavigationCompleted, which fires on the first terminal navigation event; if no initial load was requested, completion is immediate. This prevents a consumer’s first real navigation from racing renderer startup.

Sources: HeadlessInAppWebViewManager.java, InAppWebView.java

HeadlessWebViewContainer adds a non-focusable, non-touchable WindowManager window positioned off-screen. It late-binds an activity window when the first container was created from the application context, avoiding a permanently windowless container while never allowing window attachment failure to crash the app.

Sources: HeadlessWebViewContainer.java, HeadlessWebViewContainer.java

When a headless instance becomes a visible platform view, disposeAndGetFlutterWebView() restores match-parent layout, removes the view from its old parent, and nulls the wrapper’s flutterWebView reference before disposal so the transferred WebView is not destroyed. The factory then treats it as an existing instance and skips the initial load.

Sources: HeadlessInAppWebView.java, FlutterWebViewFactory.java

Keep-Alive and Input/Composition Lifecycle

Section titled “Keep-Alive and Input/Composition Lifecycle”

FlutterWebView.dispose() only destroys the contained WebView when keepAliveId is null. Likewise, Flutter-view detachment destroys the WebView only for non-kept-alive instances. Kept-alive instances therefore survive view detachment and are removed explicitly through the manager’s disposeKeepAlive path.

Sources: FlutterWebView.java, InAppWebViewManager.java

InputAwareWebView exists for pre-N input-connection behavior and virtual-display composition. It mirrors Chromium’s proxy input connection onto the IME thread, locks that connection during resize-sensitive intervals, and resets it when focus leaves the WebView. Hybrid composition bypasses these proxy paths.

Sources: InputAwareWebView.java, InputAwareWebView.java

InAppBrowserManager serializes browser creation arguments into an activity Bundle and launches InAppBrowserActivity. Its system-browser path resolves candidate activities and excludes the current package when possible, preventing accidental recursive launches of the host app.

Sources: InAppBrowserManager.java, InAppBrowserManager.java

The Android manifest declares the in-app browser, transparent Custom Tabs and Trusted Web Activity variants, single-instance variants, the action receiver, Flutter embedded-view preview support, and the AndroidX drop-data provider. These declarations are part of the native contract; browser features cannot work when the host manifest merger drops them.

Sources: AndroidManifest.xml

Process services use AndroidX and SDK feature gates rather than assuming every device exposes the same WebView capabilities. ProxyManager, for example, initializes ProxyController only when PROXY_OVERRIDE is supported and reports false when unavailable. MyCookieManager lazily initializes the Chromium cookie manager and handles missing WebView packages without treating every initialization failure as fatal.

Sources: ProxyManager.java, MyCookieManager.java

InAppWebView.dispose() is main-thread-affine: a background-thread call reposts itself to the main looper. It then disposes the channel first, stops loading, removes callbacks, clears JavaScript callback maps and web-message objects, disables JavaScript, removes the bridge interface, installs dummy clients, disposes controllers and real clients, removes window messages and views, clears history, and immediately calls destroy().

Sources: InAppWebView.java, InAppWebView.java

Disposal intentionally does not clear the HTTP cache. Android’s WebView HTTP cache is application-wide, so wiping it during every instance disposal would damage unrelated WebViews; explicit cache clearing remains available through clearAllCache().

Sources: InAppWebView.java, InAppWebViewManager.java

The native build targets Java 17, compileSdk 36, and minSdk 24, with AndroidX WebKit 1.15.0 and browser 1.8.0. Java unit tests exist for bundle and cookie utilities, while behavioral contracts for headless lifecycle, browser close behavior, controller calls, and bridge registration are exercised from the package’s Dart test suite.

Sources: build.gradle, test directory

After this page, inspect Apple Native Layer (Swift and Swift Package Manager) for the contrasting native client architecture, then Disposal Lifecycle and KeepAlive Patterns for cross-platform lifecycle semantics. For verification commands and platform-specific test boundaries, continue to Testing Strategy and Per-Package Commands.