October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
Android

How to Take Screenshots Programmatically on Android: MediaProjection vs. PixelCopy

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.

For a still image of your app’s own window or SurfaceView, use PixelCopy. To capture the device display or a user-selected app window, use MediaProjection and obtain the user’s approval for each capture session. These APIs serve different jobs: PixelCopy returns a bitmap from a particular surface, while MediaProjection sends display frames to an output such as an ImageReader. There is no general-purpose Android screenshot API that silently captures another app’s screen.

Choose the Android screenshot method that matches your target

Need Use Scope and output Important constraint
Capture your Activity window for a feedback report or UI test PixelCopy A still bitmap copied asynchronously from a Window Available from API 24; the window must have drawn and have a backing surface.
Capture a rendered SurfaceView PixelCopy A still bitmap copied from that surface Available from API 24; the surface must contain available pixel data.
Capture the full device display, or let the user choose an app window MediaProjection A media stream delivered to an ImageReader, recorder, or other supported consumer Requires explicit system-mediated user consent for each new session.
Save a small view hierarchy rendered by software View.draw() on a software Canvas A bitmap rendered from your own views Hardware-only rendering effects might not be represented correctly; drawing-cache APIs are deprecated from API 28.

MediaProjection has existed since Android 5 (API 21). PixelCopy is the better choice for a one-off still from your own window or surface; it avoids setting up a display-capture session. Use MediaProjection for capture beyond your own rendered surface, including repeated frames for recording, OCR, streaming, or screen sharing.

Capture your Activity window with PixelCopy

PixelCopy is asynchronous: submit a request with a destination bitmap and handle the result in its callback. Call it only after your Activity window has been attached and drawn. A request made too early can fail because the window has no acquired backing surface or has not produced data yet.

import android.app.Activity
import android.graphics.Bitmap
import android.os.Handler
import android.os.Looper
import android.view.PixelCopy
import android.view.Window

fun captureWindow(activity: Activity, onResult: (Bitmap?) -> Unit) {
    val window: Window = activity.window
    val decor = window.decorView

    if (decor.width == 0 || decor.height == 0) {
        onResult(null)
        return
    }

    val bitmap = Bitmap.createBitmap(
        decor.width,
        decor.height,
        Bitmap.Config.ARGB_8888
    )

    PixelCopy.request(window, bitmap, { result ->
        if (result == PixelCopy.SUCCESS) {
            onResult(bitmap)
        } else {
            bitmap.recycle()
            onResult(null)
        }
    }, Handler(Looper.getMainLooper()))
}

This function returns the captured bitmap through a callback; it does not write a file. Handle the bitmap on the caller side according to your app’s storage and sharing design. For a partial capture, use the PixelCopy overload with a source rectangle. The source region is scaled to the destination bitmap and converted to its bitmap configuration, so choose the destination dimensions and configuration intentionally.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Samsung Galaxy A17 5G Smart Phone 128GB US 1 Yr Manufacturer Warranty Black
  • YOUR CONTENT, SUPER SMOOTH: The ultra-clear 6.7" FHD+ Super AMOLED display of Galaxy A17 5G helps bring your content to life, whether you're scrolling through recipes or video chatting with loved ones.¹
  • LIVE FAST. CHARGE FASTER: Focus more on the moment and less on your battery percentage with Galaxy A17 5G. Super Fast Charging powers up your battery so you can get back to life sooner.²
  • MEMORIES MADE PICTURE PERFECT: Capture every angle in stunning clarity, from wide family photos to close-ups of friends, with the triple-lens camera on Galaxy A17 5G.
  • NEED MORE STORAGE? WE HAVE YOU COVERED: With an improved 2TB of expandable storage, Galaxy A17 5G makes it easy to keep cherished photos, videos and important files readily accessible whenever you need them.³
  • BUILT TO LAST: With an improved IP54 rating, Galaxy A17 5G is even more durable than before.⁴ It’s built to resist splashes and dust and comes with a stronger yet slimmer Gorilla Glass Victus front and Glass Fiber Reinforced Polymer back.

Copy a SurfaceView instead

Use the PixelCopy overload that takes the SurfaceView when the pixels you need are rendered into that view’s surface rather than the Activity window. Supply a destination bitmap and handle the callback result in the same way. The surface must be valid and have produced data; a newly created or unavailable surface can return an error rather than an image.

Interpret PixelCopy results

Check the result code rather than treating every callback as a successful image. PixelCopy can report SUCCESS, ERROR_SOURCE_INVALID, ERROR_SOURCE_NO_DATA, ERROR_DESTINATION_INVALID, ERROR_TIMEOUT, or ERROR_UNKNOWN. A successful request gives you a bitmap; an error means you should not publish the destination bitmap as a valid screenshot.

Capture the display or a selected app with MediaProjection

MediaProjection is the system-approved route to display capture. The user approves the capture in Android’s system flow, and on Android 14 (API 34) can select a single app window. In app-window mode, system bars, notifications, and other system UI are excluded from the captured app content. The size can differ from the full display and can change during capture.

Request consent and create the output

  1. Get MediaProjectionManager from the MEDIA_PROJECTION_SERVICE system service.
  2. Launch createScreenCaptureIntent() and wait for the activity result. Do not try to start a new session without a new user approval.
  3. Pass the returned result code and intent to getMediaProjection() exactly once for that session.
  4. Create an ImageReader at the intended width and height. Its surface is the output for the virtual display. A recorder or SurfaceTexture can be used when they better fit the application.
  5. Create the virtual display using that output surface, then consume frames from the reader.
val projection = projectionManager.getMediaProjection(resultCode, resultData)
val imageReader = ImageReader.newInstance(
    width,
    height,
    PixelFormat.RGBA_8888,
    2
)
val virtualDisplay = projection.createVirtualDisplay(
    "Screenshot",
    width,
    height,
    densityDpi,
    DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
    imageReader.surface,
    null,
    null
)

This is the core setup, not a complete Activity: your application still has to implement the consent-result flow, choose current dimensions and density, register the projection callback, consume and close images, and release resources when capture stops. On Android 14-targeting apps, the capture service must also meet the foreground-service requirements below.

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
Tracfone Motorola Moto G 2025, 64GB, Saphire Blue (Locked to
  • Carrier: This phone is locked to Tracfone, which means this device can only be used on the Tracfone wireless network. Tracfone plan required, activating is easy, just 3 steps.
  • DISPLAY: Immersive viewing on a 6.7-inch super-bright 120Hz display with powerful stereo speakers and Bass Boost for cinematic entertainment.
  • CAMERA SYSTEM: Advanced 50MP Quad Pixel camera captures sharp, detailed photos and videos in any lighting condition
  • PERFORMANCE: Lightning-fast 5G connectivity paired with a powerful processor and RAM Boost for smooth multitasking.
  • BATTERY LIFE: Long-lasting 5000mAh battery with TurboPower charging technology delivers hours of power in minutes.

Read frames without leaking ImageReader buffers

Register an ImageReader.OnImageAvailableListener, acquire the newest available image, copy its pixels, and close the image promptly. Do not retain an open Image while doing slow processing: the reader has a bounded number of image buffers, and failing to release them can prevent later frames from arriving.

imageReader.setOnImageAvailableListener({ reader ->
    val image = reader.acquireLatestImage() ?: return@setOnImageAvailableListener
    try {
        val plane = image.planes[0]
        val pixelStride = plane.pixelStride
        val rowStride = plane.rowStride
        val rowPadding = rowStride - pixelStride * image.width
        val paddedWidth = image.width + rowPadding / pixelStride

        val padded = Bitmap.createBitmap(
            paddedWidth,
            image.height,
            Bitmap.Config.ARGB_8888
        )
        plane.buffer.rewind()
        padded.copyPixelsFromBuffer(plane.buffer)

        val screenshot = Bitmap.createBitmap(
            padded,
            0,
            0,
            image.width,
            image.height
        )
        padded.recycle()

        // Process or save screenshot here, without retaining the Image.
        onScreenshot(screenshot)
    } finally {
        image.close()
    }
}, handler)

The buffer’s row stride can be wider than the visible image width. The padding calculation above creates a bitmap wide enough to copy the rows, then crops it to the actual image dimensions. Keep this stride handling; assuming tightly packed rows can produce distorted or misaligned output.

Use current dimensions and respond to app-window resizing

For initial display dimensions, use WindowManager.getMaximumWindowMetrics() and the returned WindowMetrics.getBounds(). A selected app window can have different bounds. On Android 14 and later, implement MediaProjection.Callback.onCapturedContentResize() and resize both the virtual display and the output surface when the captured content changes size; otherwise the image can be letterboxed or use stale dimensions. Also handle onCapturedContentVisibilityChanged() so a preview can be hidden or shown when the captured app is fully covered.

Android 14 foreground service and one-use token rules

Apps targeting Android 14 or later must declare android.permission.FOREGROUND_SERVICE and android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION, and the foreground service used for projection must specify android:foregroundServiceType="mediaProjection". Android 14 also makes a projection token one-use for creating a virtual display: request a fresh consent result for each new projection session, and do not reuse a prior result to create another virtual display.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Samsung Galaxy A17 5G Smart Phone 128GB, US 1 Yr Manufacturer Warranty Blue
  • YOUR CONTENT, SUPER SMOOTH: The ultra-clear 6.7" FHD+ Super AMOLED display of Galaxy A17 5G helps bring your content to life, whether you're scrolling through recipes or video chatting with loved ones.¹
  • LIVE FAST. CHARGE FASTER: Focus more on the moment and less on your battery percentage with Galaxy A17 5G. Super Fast Charging powers up your battery so you can get back to life sooner.²
  • MEMORIES MADE PICTURE PERFECT: Capture every angle in stunning clarity, from wide family photos to close-ups of friends, with the triple-lens camera on Galaxy A17 5G.
  • NEED MORE STORAGE? WE HAVE YOU COVERED: With an improved 2TB of expandable storage, Galaxy A17 5G makes it easy to keep cherished photos, videos and important files readily accessible whenever you need them.³
  • BUILT TO LAST: With an improved IP54 rating, Galaxy A17 5G is even more durable than before.⁴ It’s built to resist splashes and dust and comes with a stronger yet slimmer Gorilla Glass Victus front and Glass Fiber Reinforced Polymer back.
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />

<service
    android:name=".ScreenCaptureService"
    android:exported="false"
    android:foregroundServiceType="mediaProjection" />

The additional media-projection permission and service type are the Android 14-targeting requirements described here; they do not replace the user’s consent dialog. Build the service lifecycle around the consent result and the projection’s stop callback rather than assuming capture will run indefinitely.

Stop capture cleanly and handle lifecycle changes

Register a MediaProjection.Callback before relying on the projection. Android can stop projection when the user ends sharing, the screen locks, another projection starts, or the process dies. In onStop(), release the virtual display, close the ImageReader, discard the projection reference, and stop any associated capture work. Close individual images after each frame as well.

Make cleanup idempotent: user cancellation, an error, and the projection callback can all converge on teardown. Clear references after releasing resources so later code cannot accidentally process frames from an ended session. Do not treat process survival or a fixed display size as guaranteed.

Or skip the browser setup: use ScreenshotNeo for website screenshots

ScreenshotNeo is a website screenshot API, not an Android device-display capture API. It cannot replace MediaProjection or PixelCopy when you need pixels from a running Android app. It is relevant when your Android workflow needs an image or PDF of a public website rendered by a remote browser. See ScreenshotNeo and the API documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
Samsung Galaxy S26 Ultra, Unlocked Android Smartphone, 512GB, Black
  • PRIVACY DISPLAY: Automatically hide your screen from those beside you. The built-in privacy display can be preset¹ to turn on when receiving notifications, typing passwords, or using specific apps
  • TYPE IT IN. TRANSFORM IT FAST: Enhance any shot in seconds on your smartphone by using Photo Assist² with Galaxy AI.³ Add objects, restore details, or apply new styles by simply typing or tapping
  • NIGHTS, CAPTURED CLEARLY: From gigs to city lights, record and capture moments after dark with clarity using Nightography so your photos and videos stay crisp and clear on your Samsung Galaxy
  • MAKE IT. EDIT IT. SHARE IT: Turn everyday moments into something personal with creative tools built right into your mobile phone, whether it’s a special contact photo, custom wallpaper, an invitation or more⁴
  • HELP THAT KEEPS UP: Stay in the moment while Now Nudge with Galaxy AI helps you respond faster and stay organized with smart suggestions⁵ that appear exactly when you need them on your phone
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Replace the target URL with the website you need to capture and supply your API key. ScreenshotNeo can accept cookie or consent banners and remove known consent platforms, newsletter popups, and chat widgets before capture; those steps can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and responses identify the page verdict and billing status in headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for AI agents using Claude, Cursor, or another MCP client. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots.

Sign up free for 1,000 screenshots a month with no card.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common capture failures

  • PixelCopy returns ERROR_SOURCE_INVALID. The source surface or window is invalid or unavailable. For a window, check that the DecorView exists and the backing surface has been acquired; wait for the Activity to attach and draw before requesting a copy.
  • PixelCopy returns ERROR_SOURCE_NO_DATA. The source has not produced usable pixels yet. Retry after a draw or after the surface has rendered content instead of treating an empty frame as a screenshot.
  • PixelCopy returns ERROR_DESTINATION_INVALID. Check that the destination bitmap is valid and has usable dimensions and configuration for the request.
  • PixelCopy reports ERROR_TIMEOUT or ERROR_UNKNOWN. Do not use the destination as a successful capture. Check source availability and request timing, and report or retry the failure as appropriate to the feature.
  • MediaProjection consent succeeds but virtual-display creation fails on Android 14. Confirm that the result token is being used only once for that session and request consent again for a fresh session.
  • Capture stops unexpectedly. The user may have ended it, the screen may have locked, another projection may have started, or the process may have died. Use onStop() for cleanup and require a new consent flow before starting another session.
  • App-window output has blank margins or the wrong dimensions. Selected content may not match full-display dimensions or may have resized. On Android 14+, respond to onCapturedContentResize() by resizing the output surface and virtual display.
  • Frames stop arriving or buffers are exhausted. Close every acquired Image promptly and avoid holding images while doing slow work. Use acquireLatestImage() when the goal is the freshest frame rather than processing a backlog.

Performance, reliability, and cost considerations

PixelCopy is usually the smaller implementation for a single in-app still: it avoids a projection session and gives a bitmap through an asynchronous callback. MediaProjection is a streaming capture mechanism, so it brings consent UI, a virtual display, output-buffer management, lifecycle handling, and (for Android 14-targeting apps) foreground-service configuration. No universal speed or memory figure applies: bitmap dimensions, frame rate, image processing, and device behavior all affect resource use.

Estimate bitmap memory from its dimensions and pixel format before allocating large outputs. A stream can produce frames faster than downstream encoding or analysis can consume them, so process only what the feature needs and promptly close input images. For one still, avoid maintaining a continuous projection if PixelCopy can capture the required window or surface. Both APIs are platform APIs rather than a required paid screenshot service; cost depends on the application’s own processing and distribution choices.

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

FAQ

Can an Android app take a screenshot of another app without asking?

For device-display or selected-app capture through MediaProjection, the system requires user consent. PixelCopy is for a specific window or surface your app can access; it is not a silent substitute for cross-app screen capture.

Best Value
Tracfone Moto g Play 2024 Prepaid Phone with a 1-Yr Plan Included
  • Carrier: This phone is locked to Tracfone, which means this device can only be used on the Tracfone wireless network. Activating is easy, just 3 steps.
  • ACTIVATION Promotion: Includes 1500 min, 1500 texts & 1500 MB Data + add more as you need it
  • CAMERA SYSTEM: 50MP Quad Pixel camera. Capture sharper, more vibrant photos day or night with 4x the light sensitivity.
  • PERFORMANCE: Blazing-fast Qualcomm performance. Get the speed you need for great entertainment with a Snapdragon 680 processor and 4GB of RAM.
  • 64GB built-in storage. Get plenty of room for photos, movies, songs, and apps. Made for US

Can PixelCopy capture an entire Android screen?

PixelCopy copies from a particular Window, SurfaceView, or Surface. For a device display or user-selected app capture, use MediaProjection instead.

Should I use the View drawing cache for screenshots?

No. Drawing-cache APIs are deprecated from API 28. For a still UI screenshot, Android’s View guidance recommends PixelCopy for feedback reports or unit testing; a software Canvas and View.draw() can be useful for a small view hierarchy, with rendering limitations.

Does MediaProjection always capture system UI?

It depends on the capture scope. Android 14’s user-selected app-window mode excludes system bars, notifications, and other system UI from that app-window capture.

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

Quick Recap

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Read next

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.