首先,在 Android 清单文件 (AndroidManifest.xml) 中添加以下权限请求:
1
| <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
动态申请权限
1 2 3 4
| if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE), MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE) return }
|
查询系统 MediaStore 的 Images 表来获取所有截图的 Uri,你可以通过设置 selection 条件来只获取截图。这里假设截图保存在 “Screenshots” 文件夹中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| val projection = arrayOf( MediaStore.Images.Media._ID, MediaStore.Images.Media.BUCKET_DISPLAY_NAME, MediaStore.Images.Media.DATE_TAKEN ) val cursor = contentResolver.query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, MediaStore.Images.Media.BUCKET_DISPLAY_NAME + " LIKE ?", arrayOf("%Screenshots%"), MediaStore.Images.Media.DATE_TAKEN + " DESC" ) val screenshotUris = ArrayList<Uri>() if (cursor != null) { val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID) while (cursor.moveToNext()) { val id = cursor.getLong(idColumn) val uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id) screenshotUris.add(uri) Log.d("测试:screenshotUri",uri.toString()) } cursor.close() } Log.d("测试:screenshotUris 数量",screenshotUris.size.toString())
|