You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何获取Activity截图后的图片URL及设备刚截取的截图URL?

Hey there! Let’s break down your two screenshot-related tasks clearly—both are straightforward once you know the right APIs to use.

1. Get the Image URL After Capturing a Screenshot in an Android Activity

When you take a screenshot of your Activity, you’ll first capture the view as a Bitmap, save it to a file, then convert that file’s location into a usable URL (typically a content:// URI, which is the recommended approach for Android’s security model).

Step-by-Step Implementation

First, here’s a function to capture the Activity’s screen and return its URL:

private fun captureScreenAndGetUrl(): String? {
    // Capture the root view of your Activity
    val rootView = window.decorView.rootView
    rootView.isDrawingCacheEnabled = true
    val screenshotBitmap = Bitmap.createBitmap(rootView.drawingCache)
    rootView.isDrawingCacheEnabled = false

    // Save the Bitmap to a private app directory (avoids permission issues)
    return try {
        val screenshotDir = File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "AppScreenshots")
        if (!screenshotDir.exists()) screenshotDir.mkdirs()

        val timestamp = System.currentTimeMillis()
        val screenshotFile = File(screenshotDir, "app_screenshot_$timestamp.png")

        val outputStream = FileOutputStream(screenshotFile)
        screenshotBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
        outputStream.flush()
        outputStream.close()

        // Convert the file to a content URI (safe for app access/sharing)
        val contentUri = FileProvider.getUriForFile(this, "${packageName}.fileprovider", screenshotFile)
        contentUri.toString() // This is your "URL"
    } catch (e: IOException) {
        e.printStackTrace()
        null
    }
}

Required Configuration for FileProvider

To use FileProvider (required for generating content:// URIs on Android 7.0+), add this to your AndroidManifest.xml:

<application>
    <!-- ... other app components ... -->
    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>
</application>

Then create res/xml/file_paths.xml to define the directory your screenshots are saved in:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-files-path name="app_screenshots" path="AppScreenshots" />
</paths>

Note: The returned URL will be in the format content://your.package.name/fileprovider/app_screenshots/app_screenshot_1234567890.png, which is safe to use within your app or for sharing with other apps.


2. Retrieve the URL of the Device’s Most Recent Unprocessed Screenshot

To get the latest screenshot taken on the device (regardless of which app took it) without any Bitmap processing, we’ll query the MediaStore—this gives us direct access to the original file’s URI.

Implementation

Here’s a function to fetch the most recent screenshot’s URL:

private fun getLatestDeviceScreenshotUrl(): String? {
    val projection = arrayOf(
        MediaStore.Images.Media._ID,
        MediaStore.Images.Media.DISPLAY_NAME,
        MediaStore.Images.Media.DATE_MODIFIED
    )

    // Filter for files with "screenshot" in their name (case-insensitive)
    val selection = "${MediaStore.Images.Media.DISPLAY_NAME} LIKE ?"
    val selectionArgs = arrayOf("%screenshot%")

    // Sort by modification date, newest first
    val sortOrder = "${MediaStore.Images.Media.DATE_MODIFIED} DESC"

    contentResolver.query(
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
        projection,
        selection,
        selectionArgs,
        sortOrder
    )?.use { cursor ->
        if (cursor.moveToFirst()) {
            val imageId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID))
            val contentUri = ContentUris.withAppendedId(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                imageId
            )
            return contentUri.toString() // This is the original screenshot's URL
        }
    }
    return null
}

Required Permissions

Add these permissions to your AndroidManifest.xml to access the device’s media:

<!-- For Android 10-12 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32" />
<!-- For Android 13+ -->
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" android:minSdkVersion="33" />

Important: This returns the URI of the original screenshot file (no Bitmap processing involved), which is perfect for your validation use case. Just make sure to request the necessary runtime permissions before calling this function.


内容的提问来源于stack exchange,提问作者iamavdhesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:33:07