Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“Screenshot API for Kotlin” can mean four different jobs: capturing the current Android device screen in a test, rendering one view or Compose node, detecting that a user took a screenshot, or sending a website URL to a hosted renderer. This guide starts with the official AndroidX test capture, then covers Android 14 detection and remote website screenshots so you can choose the API that matches your outcome.

How do I take a screenshot in Kotlin?

For an instrumentation or debugging test that needs the whole visible device screen, AndroidX provides the experimental takeScreenshot() function. It returns a Bitmap and is documented for debugging scenarios, not as a production end-user screenshot feature.

Minimal AndroidX instrumentation example

import androidx.test.core.app.takeScreenshot
import org.junit.Test

class ScreenshotTest {
    @Test
    fun captureCurrentDeviceScreen() {
        val bitmap = takeScreenshot()
        // Inspect the Bitmap, save it, or pass it to a test helper.
    }
}

The function is in the androidx.test:core artifact. Add the AndroidX test core dependency that matches the rest of your test stack, and call it from an instrumentation/test context where UiAutomation is available.

Important constraints

  • takeScreenshot() is experimental; opt in if your Kotlin and dependency versions require an experimental-API annotation.
  • Do not call it on the main thread. Main-thread use is documented to throw IllegalStateException.
  • It is not safe for concurrent calls. Serialize screenshot operations in your test suite.
  • A UiAutomation capture failure can surface as a RuntimeException; treat that as an environment or capture failure rather than a bad assertion.
  • The implementation forces the app’s root views to redraw and handles disabled hardware rendering to improve stability.

This gives you a bitmap of the device screen at the time of capture. It does not upload the image, create a PDF, or provide a user-facing sharing flow; those are separate responsibilities you must implement.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

How do I capture an Android screen in an instrumentation test?

Use whole-device capture only when the test really needs the complete screen, including system bars or multiple views. For visual validation of one widget, AndroidX recommends a targeted capture instead.

Capture only the view or Compose node under test

For a classic View, use the targeted capture API named by the AndroidX reference (such as captureToBitmap). For Jetpack Compose, use the corresponding node image API (such as captureToImage). These approaches reduce unrelated pixels and make golden-image comparisons less fragile. The exact helper and test rule depend on the AndroidX testing libraries and Compose version in your project, so keep the API version aligned with your build.

A reliable test sequence

  1. Launch the Activity and wait for the UI state you intend to verify.
  2. Perform all taps, text entry, navigation, and synchronization before capture.
  3. Run the capture off the main thread and ensure no other test is capturing concurrently.
  4. Write the returned Bitmap to your test artifact directory or pass it directly to an image assertion.
  5. On failure, retain the bitmap and the test log so the visual difference can be inspected.

Saving a Bitmap in a test helper

import android.graphics.Bitmap
import java.io.File
import java.io.FileOutputStream

fun Bitmap.writePng(file: File) {
    file.parentFile?.mkdirs()
    FileOutputStream(file).use { output ->
        compress(Bitmap.CompressFormat.PNG, 100, output)
    }
}

Call bitmap.writePng(...) from your test’s artifact-writing code. PNG is lossless and usually preferable for pixel assertions; JPEG introduces compression differences.

How do I detect when a user takes a screenshot?

Android 14 introduced a privacy-preserving screenshot detection API. It reports that a supported user screenshot occurred while a particular Activity was visible, but it does not provide the image. Detection and capture are therefore different operations.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Register and unregister with the Activity lifecycle

private val screenCaptureCallback = Activity.ScreenCaptureCallback {
    // Respond to the event. The screenshot image is not provided.
}

override fun onStart() {
    super.onStart()
    registerScreenCaptureCallback(mainExecutor, screenCaptureCallback)
}

override fun onStop() {
    super.onStop()
    unregisterScreenCaptureCallback(screenCaptureCallback)
}

Declare the permission in the manifest:

<uses-permission android:name="android.permission.DETECT_SCREEN_CAPTURE" />

Register while the Activity is started and unregister when it stops. The system displays a notice for each detection signal, so explain in your UI why your app reacts (for example, offering a copy-link action or warning about sensitive data).

What this callback does not detect

The documented signal covers the specified hardware-button screenshot combination. It does not report screenshots made with ADB commands or instrumentation tests that capture the current screen. If your requirement is to stop content from appearing in screenshots, use the documented FLAG_SECURE window protection. That is a capture restriction, not an event detector.

Which Kotlin screenshot approach should I choose?

Goal API or service Result Execution and constraints
Debug or assert the complete Android screen AndroidX takeScreenshot() Bitmap Instrumentation/test context; experimental; never main thread; no concurrent calls
Assert one View or Compose node Targeted capture such as captureToBitmap or captureToImage Image of the selected UI Best for focused visual validation; API availability follows your AndroidX/Compose versions
Know that a user captured the Activity Android 14 ScreenCaptureCallback Event only, no image Activity lifecycle registration and DETECT_SCREEN_CAPTURE permission
Render a website URL Hosted or self-hosted screenshot service PNG, JPEG, WebP, or PDF, depending on service External endpoint, authentication, network and page-rendering behavior

How do I capture a website screenshot from Kotlin?

A website screenshot service renders a remote URL in a browser environment; it does not capture your Android app’s current screen. One vendor, Screenshot API, lists an “Official” Kotlin SDK for Android, Ktor, and Spring Boot with implementation 'org.screenshot-api:kotlin-sdk:1.0.0'. Treat that coordinate and version as a vendor claim: verify that the artifact is available and current in your repository before making it a production dependency. The vendor also says its REST API can be called from any language, which lets Kotlin applications avoid SDK coupling.

A self-hosted Kotlin/Ktor option

The separate screenshottech/screenshot-api GitHub project describes a Kotlin/Ktor screenshot-generation service. Its README gives ./gradlew run as a local start command, documents Docker startup options, and shows a POST /api/v1/screenshots request with an API key. It claims PNG, JPEG, WEBP, and PDF output plus full-page and viewport capture. These are project documentation claims, and this project is not established as related to the vendor SDK above; do not mix their package names, endpoints, or authentication instructions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Calling a REST endpoint from Kotlin with Ktor

import io.ktor.client.HttpClient
import io.ktor.client.request.forms.submitForm
import io.ktor.http.Parameters

suspend fun requestWebsiteScreenshot(
    client: HttpClient,
    endpoint: String,
    apiKey: String,
    pageUrl: String
): ByteArray {
    return client.submitForm(
        url = endpoint,
        formParameters = Parameters.build {
            append("api_key", apiKey)
            append("url", pageUrl)
        }
    ).readBytes()
}

Adapt parameter names, authentication, output selection, and response handling to the service you actually deploy. Keep API keys on a server rather than shipping them in an Android APK. Set connection and request timeouts, validate the target URL, and impose a response-size limit before writing bytes to storage.

Or skip the browser setup

ScreenshotNeo is a hosted website screenshot API and MCP server. It accepts a URL and returns PNG, JPEG, WebP, or PDF without requiring you to operate a browser farm. Its clean-shot workflow accepts cookie or consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status.

From Kotlin, the simplest integration is an HTTP GET. See the ScreenshotNeo API documentation for the current parameters.

import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.nio.file.Files
import java.nio.file.Path

fun main() {
    val apiKey = System.getenv("SCREENSHOTNEO_API_KEY")
        ?: error("Set SCREENSHOTNEO_API_KEY")
    val target = "https://stripe.com"
    val requestUri = URI.create(
        "https://api.screenshotneo.com/v1/shot" +
            "?access_key=$apiKey&url=" +
            java.net.URLEncoder.encode(target, Charsets.UTF_8)
    )
    val request = HttpRequest.newBuilder(requestUri).GET().build()
    val response = HttpClient.newHttpClient().send(
        request,
        HttpResponse.BodyHandlers.ofByteArray()
    )
    require(response.statusCode() in 200..299) {
        "Screenshot request failed: ${response.statusCode()}"
    }
    Files.write(Path.of("shot.webp"), response.body())
}

ScreenshotNeo also supports full-page capture with lazy images loaded, CSS-selector element capture, dark mode, 12 device presets or custom viewports, retina scale, PDF paper size/margins/orientation/page ranges, custom CSS and JavaScript, pre-capture clicks, hidden selectors, waits for a selector/delay/network idle, ad/tracker/request/resource blocking, custom headers/cookies/user agents/Authorization, timezone and geolocation, transparent backgrounds, image resizing, configurable-TTL caching, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, an OpenAPI specification, and compatibility with parameter names used by other screenshot APIs. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Plans include 1,000 screenshots per month free with no card, Starter at $5 for 3,000, Growth at $15 for 15,000, Pro at $39 for 60,000, Scale at $99 for 250,000, and Business at $249 for 1,000,000; annual billing provides two months free. Every feature is included on every plan. Create a free ScreenshotNeo account to start with the 1,000 free monthly screenshots.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting Kotlin screenshot captures

IllegalStateException from AndroidX capture

Move the call off the main thread and ensure the test is running with instrumentation support. A main-thread call is a documented failure mode.

Intermittent or corrupted images

Serialize calls, wait for the UI to reach a deterministic state, and avoid capturing during transitions or animations. Whole-screen capture triggers a redraw, so allow pending layout work to settle before asserting pixels.

Screenshot callback never fires

Check that the device is running Android 14 or later, the manifest contains DETECT_SCREEN_CAPTURE, registration occurs in onStart(), and unregistration occurs in onStop(). The callback will not report ADB or instrumentation captures.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Remote service returns an error or HTML instead of an image

Verify the endpoint, authentication, URL encoding, timeout, and response content type. Keep secrets server-side, log status and provider headers, and check whether the target page blocks automation or requires cookies, headers, geolocation, or a longer wait.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

SDK dependency cannot be resolved

Re-check the vendor’s repository, group ID, artifact ID, and version. The listed org.screenshot-api:kotlin-sdk:1.0.0 coordinate is vendor documentation, not a guarantee that your configured repositories still serve it.

Performance, reliability, and security notes

  • Capture the smallest useful surface: a node or view is cheaper to compare and less sensitive to unrelated layout changes than a full device image.
  • Use PNG for exact visual assertions and JPEG/WebP when transfer size matters more than lossless pixels.
  • For website rendering, define explicit waits and viewport/device settings; otherwise asynchronous fonts, images, consent dialogs, and responsive breakpoints can change output.
  • Cache only when the page’s freshness requirements allow it. For authenticated pages, protect cookies, Authorization headers, signed links, and generated files as secrets.
  • Never place a hosted-service API key in an Android client distributed to users. Proxy requests through a controlled backend and apply URL allow-lists where users can submit targets.

Frequently Asked Questions

Can AndroidX takeScreenshot be used in a released app?

It is documented for instrumentation and debugging contexts. It is not presented as a production end-user screenshot or screen-recording mechanism.

Does Android screenshot detection give me the captured bitmap?

No. Android 14’s callback reports a supported screenshot event only; the image is not exposed.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Are Screenshot API’s Kotlin SDK and screenshottech/screenshot-api the same project?

No relationship is established. They are separate vendor and repository claims with different installation and endpoint details.

What should I use for a website screenshot pipeline in Kotlin?

Use a hosted REST API when you do not want to run browser infrastructure; use a self-hosted Ktor service when you need to operate the renderer yourself. Keep credentials and rendering policy on a server.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.