Class CefriumBrowser
Two rendering modes are available:
- Off-screen (OSR) — frames delivered as BGRA pixel buffers
via
CefriumRenderHandler.onPaint(int, int, java.nio.ByteBuffer). Use for headless rendering, screenshots, or custom compositing. Create withCefriumBrowser(int, int, float). - Surface — hardware-accelerated rendering to an Android Surface
via ContentViewRenderView. Supports video, audio, touch, DRM.
Create with
createWithSurface(android.app.Activity).
Lifecycle: Call onPause() / onResume() from your
Activity lifecycle. Call close() when done — this releases native
resources. Do not call any method after close().
Threading: All methods must be called on the UI thread.
// Surface mode (recommended for most apps)
CefriumBrowser browser = CefriumBrowser.createWithSurface(activity);
layout.addView(browser.getSurfaceContainer());
browser.loadUrl("https://example.com");
// OSR mode (headless / screenshots)
CefriumBrowser browser = new CefriumBrowser(1080, 1920, 2.75f);
browser.setRenderHandler((w, h, pixels) -> { });
browser.loadUrl("https://example.com");
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceReceives the captured page bitmap (null on failure).static classUnified callback interface for browser events.static final classA candidate device offered to aCefriumBrowser.DeviceChooserSession.static final classAn HTTP cookie read from the browser's cookie store.static interfaceReceives the result ofgetCookies(java.lang.String, com.cefrium.CefriumBrowser.CookieCallback).static interfacePresents device chooser UI for the frontier web device APIs.static interfaceA live device chooser.static interfaceReceives the app's credentials (or cancel) for an HTTP auth challenge.static interfaceSupplies credentials for an HTTP or proxy authentication challenge (the WebViewonReceivedHttpAuthRequestequivalent).static interfaceResolves a JS dialog.static interfaceHandles page JS dialogs (alert/confirm/prompt).static interfaceListener for context menu events (long press on links/images).static interfaceListener for download progress updates.static interfaceListener for find-in-page results.static interfaceListener for fullscreen mode changes.static interfaceListener for loading state changes.static interfaceListener for renderer-process termination.static interfaceListener for network requests.static interfaceListener for title changes.static interfaceListener for URL changes.static interfacestatic interfaceReceives the app's grant/deny decision for a permission request.static interfaceDecides web permission requests (geolocation, camera, mic, ...).static interfaceHandles popups (window.open / target=_blank).static interfaceResolves aCefriumBrowser.QueryHandlerquery back to JavaScript.static interfaceHandles JavaScriptwindow.cefriumQuery({request, onSuccess, onFailure})calls from page content (the JS ↔ native bridge).static interfaceDecides whether to block outgoing requests.static interfaceReceives the app's proceed/cancel decision for an invalid certificate.static interfaceDecides whether to continue loading a URL whose TLS certificate failed validation (the WebViewonReceivedSslErrorequivalent). -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intDevice chooser kinds, passed toCefriumBrowser.DeviceChooserHandler.static final intstatic final intstatic final intalert()static final intconfirm()static final intprompt()static final intstatic final intClipboard read (navigator.clipboard.readText).static final intPermission types (bitmask, from cef_permission_request_types_t).static final intstatic final intWeb NFC (NDEFReader scan/write).static final intstatic final Stringstatic final StringProxy modes forsetProxy(String, String)(Chromium proxy modes).static final Stringstatic final Stringstatic final Stringstatic final intstatic final intstatic final intstatic final intstatic final intstatic final intstatic final intstatic final intContent setting values forsetContentSetting(java.lang.String, int, int).static final intTermination status: process exited abnormally.static final intTermination status: process crashed.static final intTermination status: process was killed (e.g.static final intTermination status: process ran out of memory. -
Constructor Summary
ConstructorsConstructorDescriptionCreate a new off-screen browser with default settings.CefriumBrowser(int width, int height) Create a new off-screen browser with specified viewport size.CefriumBrowser(int width, int height, float scale) Create a new off-screen browser with specified viewport size and device scale factor. -
Method Summary
Modifier and TypeMethodDescriptionstatic intExact number of live renderer processes the engine currently has -- countsRenderProcessHostonly, so utility/network/audio/storage and GPU child processes are NOT included (this is the clean renderer count, unlikeps | grep sandboxed_processwhich mixes them all).booleanvoidcaptureBitmap(CefriumBrowser.BitmapCallback callback) Captures the current page to aBitmap, delivered asynchronously on the main thread.voidClears the browser's HTTP cache.booleanConvenience: disable proxying (direct connection).voidclose()Close this browser and release all native resources.static intCumulative number of browsers that have finished closing (theirOnBeforeClosefired).voidcontextMenuCommand(int commandId) Send the user's context menu selection back to CEF.static CefriumBrowsercreateWithSurface(android.app.Activity activity) Create a browser that renders directly to an Android Surface.static CefriumBrowsercreateWithSurface(android.app.Activity activity, boolean incognito) LikecreateWithSurface(android.app.Activity)but for a private (incognito) tab.voiddeleteCookies(String url, String name) Deletes cookies forurl;namenull/empty = all for the URL.voidevaluateJavaScript(String script) Execute JavaScript in the browser's main frame (fire-and-forget).voidSearch for text in the current page.voidPersists the cookie store to disk.intGet the number of blocked ad/tracking requests since the browser was created.voidgetCookies(String url, CefriumBrowser.CookieCallback callback) Reads cookies visible tourl; the callback fires on the UI thread.android.widget.FrameLayoutGet the container View for Surface rendering.getUrl()The current top-level URL, ornullbefore the first navigation.voidgoBack()Navigate back in history.voidNavigate forward in history.voidForce the browser to repaint.booleanWhether the page's audio is currently muted viasetAudioMuted(boolean).booleanstatic intLive (not-yet-closed) browser instances.voidloadDataWithBaseUrl(String baseUrl, String data, String mimeType, String encoding, String historyUrl) Loads a data string with an explicit base URL, mirroring Android WebView'sWebView.loadDataWithBaseURL(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String).voidLoads an HTML string directly (served to the engine as a data: URL).voidloadHtmlWithBaseUrl(String html, String baseUrl) Convenience: load an HTML string with the given base URL (text/html, utf-8, history = baseUrl).voidNavigate to a URL.booleanonActivityResult(int requestCode, int resultCode, android.content.Intent data) Forward Activity result to the browser for intent handling (file picker, permissions, etc.).voidonPause()Convenience for "host is backgrounding": hide the page, suspend media and mute audio so inline audio/video actually stops (visibility HIDDEN alone keeps background audio playing).voidonResume()Convenience for "host is foregrounding": unmute, make the page visible and resume media suspended byonPause().voidLoadsurlwith an HTTP POST body.voidprintToPdf(String filePath, CefriumBrowser.PdfCallback callback) Renders the current page to a PDF atfilePath(async).static voidShuts down render child-processes left orphaned after browsers were closed (e.g.voidreload()Reload the current page.voidrestoreNavigationState(byte[] state) Restores a navigation stack captured byserializeNavigationState().voidrestoreState(android.os.Bundle state) Restores state previously captured bysaveState()— re-navigates to the saved URL.voidResumes media suspended bysuspendMedia()(resumes where it left off).android.os.BundleCaptures restorable browser state (the current URL) into a Bundle.voidsendTouchEvent(int action, float x, float y, int pointerId) Forward a touch event to the browser.byte[]Serializes this tab's full back/forward navigation stack (each entry's URL and blink PageState, plus the current index) for session restore.voidsetAudioMuted(boolean muted) Mutes/unmutes ALL audio output of the page (keeps media decoding/playing, just silenced).voidsetCallback(CefriumBrowser.Callback callback) Set a unified callback for all browser events.voidsetContentSetting(String requestingUrl, int permission, int value) Sets a per-origin web-permission content setting without showing a prompt.voidSets a session cookie forurl(domain/path inferred from the URL).voidSets a session cookie forurlwith explicit attributes.voidsetDarkMode(boolean dark) Set dark mode via CEF API (CefRequestContext::SetChromeColorSchemeMode).voidSets the device chooser handler (null = cancel all device requests).voidSets the HTTP auth handler (null = cancel every auth challenge).voidsetJavaScriptEnabled(boolean enabled) Enables/disables JavaScript at runtime (Emulation.setScriptExecutionDisabled).voidSets a custom JS-dialog handler (null = default Android AlertDialog).voidsetMediaSessionEnabled(boolean enabled) Enables system media controls (lock-screen + notification shade) for this browser's playback, driven by the page'snavigator.mediaSession.voidSet the listener for context menu events.voidSet the listener for download progress updates.voidSet the listener for find-in-page results.voidSet a listener for fullscreen mode changes.voidSet a listener for loading state changes.voidSet a listener notified when a renderer process for this browser dies.voidSet a listener for network request interception.voidSet a listener for title changes.voidSet a listener for URL changes during navigation.voidsetPageVisible(boolean visible) Sets the page's visibility (compositor + Page Visibility APIdocument.hidden).voidSets the permission handler (null = deny all web permission requests).voidSets a popup handler (null = load popups in this browser).booleanConvenience: route all traffic through a fixed proxy"host:port".booleanConfigures the proxy for this browser's request context.voidsetPullToRefreshEnabled(boolean enabled) Enable pull-to-refresh: an overscroll-down gesture at the top of the page reloads it (Chrome-style).voidRegisters the handler forwindow.cefriumQuerycalls.voidsetRenderHandler(CefriumRenderHandler handler) Set the render handler to receive painted frames (OSR mode only).voidsetRequestInterceptor(CefriumBrowser.RequestInterceptor interceptor) Sets a programmatic request interceptor (null clears it).voidSets the SSL/certificate error handler (null = cancel on every cert error).voidsetUserAgentOverride(String userAgent) Overrides the User-Agent at runtime (Emulation.setUserAgentOverride).voidsetZoomLevel(double zoomLevel) Sets the zoom level (0 = 100%; factor = 1.2^level).voidHard-stops all media players (not resumable likesuspendMedia()) and mutes audio.voidstopFinding(boolean clearSelection) Stop the current find-in-page search.voidStops the current load.voidStops the page's media session and dismisses its media notification.voidSuspends active media (audio + video) at the browser-process level (MediaSession Suspend == the audio-focus-loss path).static intTotal live RenderFrameHosts across all renderer processes -- the real "working frame" count (host pages + iframes).static intRenderer processes that currently host ZERO frames -- reuse "zombies" the pool's reap targets.
-
Field Details
-
TERMINATION_ABNORMAL
public static final int TERMINATION_ABNORMALTermination status: process exited abnormally.- See Also:
-
TERMINATION_KILLED
public static final int TERMINATION_KILLEDTermination status: process was killed (e.g. by the OS low-memory killer).- See Also:
-
TERMINATION_CRASHED
public static final int TERMINATION_CRASHEDTermination status: process crashed.- See Also:
-
TERMINATION_OOM
public static final int TERMINATION_OOMTermination status: process ran out of memory.- See Also:
-
SAME_SITE_UNSPECIFIED
public static final int SAME_SITE_UNSPECIFIED- See Also:
-
SAME_SITE_NONE
public static final int SAME_SITE_NONE- See Also:
-
SAME_SITE_LAX
public static final int SAME_SITE_LAX- See Also:
-
SAME_SITE_STRICT
public static final int SAME_SITE_STRICT- See Also:
-
JS_DIALOG_ALERT
public static final int JS_DIALOG_ALERTalert()- See Also:
-
JS_DIALOG_CONFIRM
public static final int JS_DIALOG_CONFIRMconfirm()- See Also:
-
JS_DIALOG_PROMPT
public static final int JS_DIALOG_PROMPTprompt()- See Also:
-
PERMISSION_GEOLOCATION
public static final int PERMISSION_GEOLOCATIONPermission types (bitmask, from cef_permission_request_types_t).- See Also:
-
PERMISSION_CAMERA
public static final int PERMISSION_CAMERA- See Also:
-
PERMISSION_MICROPHONE
public static final int PERMISSION_MICROPHONE- See Also:
-
PERMISSION_NOTIFICATIONS
public static final int PERMISSION_NOTIFICATIONS- See Also:
-
PERMISSION_CLIPBOARD
public static final int PERMISSION_CLIPBOARDClipboard read (navigator.clipboard.readText). Writing needs no prompt.- See Also:
-
PERMISSION_NFC
public static final int PERMISSION_NFCWeb NFC (NDEFReader scan/write). Also declareandroid.permission.NFCin your manifest and have NFC enabled on the device. Grant this in yourCefriumBrowser.PermissionHandler(or pre-authorize viasetContentSetting(java.lang.String, int, int)withSETTING_ALLOW).- See Also:
-
SETTING_DEFAULT
public static final int SETTING_DEFAULTContent setting values forsetContentSetting(java.lang.String, int, int).- See Also:
-
SETTING_ALLOW
public static final int SETTING_ALLOW- See Also:
-
SETTING_BLOCK
public static final int SETTING_BLOCK- See Also:
-
SETTING_ASK
public static final int SETTING_ASK- See Also:
-
PROXY_DIRECT
Proxy modes forsetProxy(String, String)(Chromium proxy modes).- See Also:
-
PROXY_SYSTEM
- See Also:
-
PROXY_AUTO_DETECT
- See Also:
-
PROXY_FIXED
- See Also:
-
PROXY_PAC
- See Also:
-
DEVICE_BLUETOOTH
public static final int DEVICE_BLUETOOTHDevice chooser kinds, passed toCefriumBrowser.DeviceChooserHandler.- See Also:
-
DEVICE_USB
public static final int DEVICE_USB- See Also:
-
DEVICE_SERIAL
public static final int DEVICE_SERIAL- See Also:
-
-
Constructor Details
-
CefriumBrowser
public CefriumBrowser()Create a new off-screen browser with default settings. -
CefriumBrowser
public CefriumBrowser(int width, int height) Create a new off-screen browser with specified viewport size. Device scale factor defaults to 1.0 (desktop). For mobile, useCefriumBrowser(int, int, float).- Parameters:
width- Viewport width in physical pixels.height- Viewport height in physical pixels.
-
CefriumBrowser
public CefriumBrowser(int width, int height, float scale) Create a new off-screen browser with specified viewport size and device scale factor.The scale factor controls how CSS pixels map to physical pixels. For example, on a 1080px wide screen with scale 2.75, the CSS viewport is ~393px — triggering mobile layouts.
- Parameters:
width- Viewport width in physical pixels.height- Viewport height in physical pixels.scale- Device scale factor (e.g., 2.75 for Xiaomi Redmi Note 13 Pro).
-
-
Method Details
-
setRenderHandler
Set the render handler to receive painted frames (OSR mode only). Each frame is a BGRA pixel buffer with dimensions matching the viewport size set in the constructor.- Parameters:
handler- The handler to receive OnPaint callbacks, or null to stop.- See Also:
-
loadUrl
Navigate to a URL. Supports http://, https://, file://, and data: URLs. If the scheme is omitted, https:// is NOT added automatically — pass the full URL.- Parameters:
url- The URL to load.
-
goBack
public void goBack()Navigate back in history. No-op ifcanGoBack()is false. -
goForward
public void goForward()Navigate forward in history. No-op if there is no forward history. -
setPullToRefreshEnabled
public void setPullToRefreshEnabled(boolean enabled) Enable pull-to-refresh: an overscroll-down gesture at the top of the page reloads it (Chrome-style). Off by default. Call this BEFORE the page loads (the handler is bound once, when the WebContents connects); it must not be toggled on a live WebContents. -
setDarkMode
public void setDarkMode(boolean dark) Set dark mode via CEF API (CefRequestContext::SetChromeColorSchemeMode). Call after browser is created and loaded.- Parameters:
dark- true for dark mode, false for light mode.
-
setCallback
Set a unified callback for all browser events. This is the recommended way to handle events. Individual setOnXxxListener methods are also available for convenience. -
setOnUrlChangedListener
Set a listener for URL changes during navigation. -
setOnTitleChangedListener
Set a listener for title changes. -
setOnFullscreenChangedListener
Set a listener for fullscreen mode changes. -
setOnRequestInterceptedListener
Set a listener for network request interception. Called for EVERY request — use for network inspection, debugging, or custom request auditing. -
getUrl
The current top-level URL, ornullbefore the first navigation. -
saveState
public android.os.Bundle saveState()Captures restorable browser state (the current URL) into a Bundle. Call fromActivity.onSaveInstanceStateand pass the result torestoreState(android.os.Bundle)after recreating the browser. -
restoreState
public void restoreState(android.os.Bundle state) Restores state previously captured bysaveState()— re-navigates to the saved URL. No-op ifstateis null or holds no saved URL. -
setOnLoadingStateChangedListener
Set a listener for loading state changes. -
setOnRenderProcessTerminatedListener
public void setOnRenderProcessTerminatedListener(CefriumBrowser.OnRenderProcessTerminatedListener listener) Set a listener notified when a renderer process for this browser dies. The native CefRequestHandler is always installed, so no extra wiring is needed -- the callback fires whenever the renderer terminates. -
reload
public void reload()Reload the current page. Uses CefBrowserHost::Reload (ignores cache). -
evaluateJavaScript
Execute JavaScript in the browser's main frame (fire-and-forget). Uses CefFrame::ExecuteJavaScript. The script's return value is not delivered back to the caller; a result-returning JS bridge is a separate feature built on CefMessageRouter.- Parameters:
script- JavaScript source to execute. Ignored if null.
-
setQueryHandler
Registers the handler forwindow.cefriumQuerycalls. -
setCookie
Sets a session cookie forurl(domain/path inferred from the URL). -
setCookie
public void setCookie(String url, String name, String value, boolean secure, boolean httpOnly, int sameSite) Sets a session cookie forurlwith explicit attributes. Use this for cookies a third-party/cross-site context must send (e.g. a consent cookie an embedded iframe needs): passsecure=trueandsameSite=SAME_SITE_NONE-- Chromium rejectsSameSite=NonewithoutSecure. domain/path are inferred from the URL. -
getCookies
Reads cookies visible tourl; the callback fires on the UI thread. -
deleteCookies
Deletes cookies forurl;namenull/empty = all for the URL. -
flushCookies
public void flushCookies()Persists the cookie store to disk. -
clearCache
public void clearCache()Clears the browser's HTTP cache. -
printToPdf
Renders the current page to a PDF atfilePath(async). -
setUserAgentOverride
Overrides the User-Agent at runtime (Emulation.setUserAgentOverride). -
setJavaScriptEnabled
public void setJavaScriptEnabled(boolean enabled) Enables/disables JavaScript at runtime (Emulation.setScriptExecutionDisabled). -
setZoomLevel
public void setZoomLevel(double zoomLevel) Sets the zoom level (0 = 100%; factor = 1.2^level). -
loadHtml
Loads an HTML string directly (served to the engine as a data: URL). -
loadDataWithBaseUrl
public void loadDataWithBaseUrl(String baseUrl, String data, String mimeType, String encoding, String historyUrl) Loads a data string with an explicit base URL, mirroring Android WebView'sWebView.loadDataWithBaseURL(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String). Unlike WebView, Cefrium delivers the content as a GENUINE network response atbaseUrl(not adata:document), so the loaded document has a real, network-served origin ==baseUrl. This is what lets inline embedded players that require a network-served parent -- notably the YouTube IFrame player -- play; adata:document is rejected by such players (Error 152), which is why the same content fails under WebView'sloadDataWithBaseURL.Origin guidance: pass your own app origin as
baseUrl(as any website embedding YouTube does), e.g."https://app.example.com"-- NOT"https://www.youtube.com". YouTube rejects same-origin self-embedding with Error 152.- Parameters:
baseUrl- network origin for the document, e.g."https://app.example.com"data- the HTML (or other) content to loadmimeType- content type, e.g."text/html"(defaults to text/html if null/empty)encoding- charset, e.g."utf-8"(defaults to utf-8 if null/empty)historyUrl- URL used for the document's virtual/history URL (defaults to baseUrl if null/empty)
-
loadHtmlWithBaseUrl
Convenience: load an HTML string with the given base URL (text/html, utf-8, history = baseUrl). The document is served from a real network origin ==baseUrl, so an inline YouTube IFrame embedded inhtmlplays. Pass YOUR OWN app origin asbaseUrl, e.g.loadHtmlWithBaseUrl("<iframe src='https://www.youtube.com/embed/ID'></iframe>", "https://app.example.com")-- not"https://www.youtube.com"(YouTube rejects same-origin self-embedding). SeeloadDataWithBaseUrl(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String). -
postUrl
Loadsurlwith an HTTP POST body. -
stopLoading
public void stopLoading()Stops the current load. -
setRequestInterceptor
Sets a programmatic request interceptor (null clears it). -
setJsDialogHandler
Sets a custom JS-dialog handler (null = default Android AlertDialog). -
setPermissionHandler
Sets the permission handler (null = deny all web permission requests). -
setContentSetting
Sets a per-origin web-permission content setting without showing a prompt. Lets an app pre-grant (or block) a permission for an origin it trusts — e.g. allow Web Notifications for your own web app sonew Notification(...)works without a runtime prompt.- Parameters:
requestingUrl- the origin URL, e.g."https://example.com"permission- one of thePERMISSION_*constants (PERMISSION_NOTIFICATIONS,PERMISSION_GEOLOCATION,PERMISSION_CAMERA,PERMISSION_MICROPHONE,PERMISSION_NFC)value- one of theSETTING_*constants (SETTING_ALLOW,SETTING_BLOCK,SETTING_ASK,SETTING_DEFAULT)
-
setProxy
Configures the proxy for this browser's request context. [mode] is one of thePROXY_*constants; [server] is"host:port"(or"scheme://host:port") forPROXY_FIXED, the PAC URL forPROXY_PAC, and ignored otherwise. Returns false if the preference could not be applied. Useful for kiosk/enterprise deployments. -
setProxy
Convenience: route all traffic through a fixed proxy"host:port". -
clearProxy
public boolean clearProxy()Convenience: disable proxying (direct connection). -
setDeviceChooserHandler
Sets the device chooser handler (null = cancel all device requests). -
setSslErrorHandler
Sets the SSL/certificate error handler (null = cancel on every cert error). -
setHttpAuthHandler
Sets the HTTP auth handler (null = cancel every auth challenge). -
setPopupHandler
Sets a popup handler (null = load popups in this browser). -
canGoBack
public boolean canGoBack()- Returns:
- true if the browser can navigate back.
-
suspendMedia
public void suspendMedia()Suspends active media (audio + video) at the browser-process level (MediaSession Suspend == the audio-focus-loss path). Position is preserved;resumeMedia()resumes. Works even after the renderer JS is suspended -- unlikeevaluateJavaScript("...pause()"), which is queued and never runs once backgrounded. -
resumeMedia
public void resumeMedia()Resumes media suspended bysuspendMedia()(resumes where it left off). -
setAudioMuted
public void setAudioMuted(boolean muted) Mutes/unmutes ALL audio output of the page (keeps media decoding/playing, just silenced). Use this for a "go quiet but keep position/time advancing" policy; usesuspendMedia()to actually pause. -
isAudioMuted
public boolean isAudioMuted()Whether the page's audio is currently muted viasetAudioMuted(boolean). -
setPageVisible
public void setPageVisible(boolean visible) Sets the page's visibility (compositor + Page Visibility APIdocument.hidden). HIDDEN saves GPU/battery and firesvisibilitychange, but does NOT by itself stop audio. -
stopAllMedia
public void stopAllMedia()Hard-stops all media players (not resumable likesuspendMedia()) and mutes audio. For "fully release audio on background" when you do not need to resume in place. -
stopMediaSession
public void stopMediaSession()Stops the page's media session and dismisses its media notification. UnlikestopAllMedia()(which pauses + mutes, leaving a paused notification), this clears the session -- for a host navigating away from a video screen that wants the tray notification gone. Operates at the WebContents level, so it also stops media in cross-origin iframes (e.g. a YouTube embed) that page JS cannot reach. -
onPause
public void onPause()Convenience for "host is backgrounding": hide the page, suspend media and mute audio so inline audio/video actually stops (visibility HIDDEN alone keeps background audio playing). Resumable viaonResume(). Call from Activity.onPause()/onStop(); the ComposeCefriumViewwires this automatically (see itsbackgroundMediaPolicy). -
onResume
public void onResume()Convenience for "host is foregrounding": unmute, make the page visible and resume media suspended byonPause(). Call from Activity.onResume()/onStart(); wired automatically byCefriumView. -
reapUnusedRenderers
public static void reapUnusedRenderers()Shuts down render child-processes left orphaned after browsers were closed (e.g. LRU eviction in a browser pool). Closing a browser destroys its WebContents but Chromium may keep the child process around; on process-per-browser devices the sandboxed process count then grows. This reaps processes with zero frames only (never a live renderer), after a short delay to let the just-closed browser tear down. Memory-neutral but keeps the process count bounded. Safe no-op on shared-renderer devices. -
activeRenderProcessCount
public static int activeRenderProcessCount()Exact number of live renderer processes the engine currently has -- countsRenderProcessHostonly, so utility/network/audio/storage and GPU child processes are NOT included (this is the clean renderer count, unlikeps | grep sandboxed_processwhich mixes them all). Excludes the spare renderer. After a browser pool settles this is approximately itsmaxAlive. Diagnostic; call on the main thread (returns -1 otherwise). -
zeroFrameRenderProcessCount
public static int zeroFrameRenderProcessCount()Renderer processes that currently host ZERO frames -- reuse "zombies" the pool's reap targets. A high value while a pool runs means orphaned renderers are lingering (reusable but not freed). Main thread only (-1 otherwise). Diagnostic. -
totalRenderFrameHostCount
public static int totalRenderFrameHostCount()Total live RenderFrameHosts across all renderer processes -- the real "working frame" count (host pages + iframes). If this grows as you open pages and never drops, the closed pages' frames are NOT being destroyed. Main thread only (-1 otherwise). Diagnostic. -
closedBrowserCount
public static int closedBrowserCount()Cumulative number of browsers that have finished closing (theirOnBeforeClosefired). If this does NOT grow as a pool evicts browsers,close()is not completing -- the page leaks. Diagnostic. -
liveBrowserCount
public static int liveBrowserCount()Live (not-yet-closed) browser instances. Diagnostic. -
close
public void close()Close this browser and release all native resources. After calling this method, no other methods may be called on this instance. For Surface mode, also removes the rendering views. -
captureBitmap
Captures the current page to aBitmap, delivered asynchronously on the main thread. In off-screen mode the next painted frame is returned; in Surface mode the visible surface is copied viaPixelCopy. The callback receives null if capture is unavailable. -
invalidate
public void invalidate()Force the browser to repaint. Call this if you need an updated frame (e.g. after content changes). -
sendTouchEvent
public void sendTouchEvent(int action, float x, float y, int pointerId) Forward a touch event to the browser.- Parameters:
action- 0=DOWN, 1=UP, 2=MOVE, 3=CANCELx- X coordinate in browser viewport pixelsy- Y coordinate in browser viewport pixelspointerId- Pointer ID for multi-touch
-
getBlockedCount
public int getBlockedCount()Get the number of blocked ad/tracking requests since the browser was created. Cefrium includes a built-in network-level ad blocker using EasyList rules.- Returns:
- Number of blocked requests, or 0 if the browser is closed.
-
createWithSurface
Create a browser that renders directly to an Android Surface. Enables video playback, audio, and hardware-accelerated compositing.All Chromium rendering infrastructure (WindowAndroid, ContentViewRenderView, ContentView) is created and managed internally. The browser view is added to the Activity's content.
CefriumBrowser browser = CefriumBrowser.createWithSurface(this); browser.setOnUrlChangedListener(url -> urlBar.setText(url)); browser.loadUrl("https://example.com");- Parameters:
activity- The Activity to render in. A FrameLayout container is returned viagetSurfaceContainer().- Returns:
- A new CefriumBrowser instance with Surface rendering.
-
createWithSurface
LikecreateWithSurface(android.app.Activity)but for a private (incognito) tab. Incognito browsers share one off-the-record session that is isolated from normal tabs; their cookies, history and cache live only in memory and are cleared when the last incognito browser is closed.- Parameters:
activity- The Activity to render in.incognito- true for a private / off-the-record browser.- Returns:
- A new CefriumBrowser instance with Surface rendering.
-
isIncognito
public boolean isIncognito()- Returns:
- true if this is a private (incognito) browser.
-
onActivityResult
public boolean onActivityResult(int requestCode, int resultCode, android.content.Intent data) Forward Activity result to the browser for intent handling (file picker, permissions, etc.). Call this from your Activity's onActivityResult.- Returns:
- true if the result was handled by the browser.
-
getSurfaceContainer
public android.widget.FrameLayout getSurfaceContainer()Get the container View for Surface rendering. Add this to your Activity's layout.- Returns:
- FrameLayout containing the browser surface.
-
setMediaSessionEnabled
public void setMediaSessionEnabled(boolean enabled) Enables system media controls (lock-screen + notification shade) for this browser's playback, driven by the page'snavigator.mediaSession. Requires thePOST_NOTIFICATIONSruntime permission on Android 13+. Safe to call before or after the page loads. -
setOnFindResultListener
Set the listener for find-in-page results. -
find
Search for text in the current page. Uses CEF API: CefBrowserHost::Find.- Parameters:
text- Text to search for. Empty string stops the search.forward- true to search forward, false to search backward.matchCase- true for case-sensitive search.findNext- true if continuing a previous search (next/prev).
-
stopFinding
public void stopFinding(boolean clearSelection) Stop the current find-in-page search. Uses CEF API: CefBrowserHost::StopFinding.- Parameters:
clearSelection- true to clear the selection highlight.
-
setOnDownloadListener
Set the listener for download progress updates. -
setOnContextMenuListener
Set the listener for context menu events. -
contextMenuCommand
public void contextMenuCommand(int commandId) Send the user's context menu selection back to CEF. Use -1 to cancel.- Parameters:
commandId- The selected command ID, or -1 to cancel.
-