android - ActivityResultContracts.TakePicture()

标签 android android-activity androidx

在 androidx.activity 版本 1.2.0-alpha05 中,TakePicture 合约的 API 已更改:

The TakePicture contract now returns a boolean indicating success rather than a thumbnail Bitmap as this was very rarely supported by camera apps when writing the image to the provided Uri



虽然在 alpha04 回调中接收到一个 Bitmap 对象,但现在回调只接收到一个描述成功的 bool 对象。

所以现在launcher的launch方法的Uri参数不能为空,必须是图片保存的目的地。没有设法创建一个启动器接受的 Uri 对象,该对象可用于我的应用程序读取结果图片。

有人可以为我提供可以提供给启动器的有效 Uri 对象的示例吗?

最佳答案

我在互联网上找不到任何示例
这是一个例子。

File file = new File(getFilesDir(), "picFromCamera");
Uri uri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", file);

ActivityResultLauncher<Uri> mGetContent = registerForActivityResult(
    new ActivityResultContracts.TakePicture(),
    new ActivityResultCallback<Boolean>() {
        @Override
        public void onActivityResult(Boolean result) {
                            
        // do what you need with the uri here ...
    }
});                        
mGetContent.launch(uri);
注意1:您可能会遇到FileUriExposedException , 需要公开这个 uri 供相机应用访问
相关:android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()
注2:如果您有<uses-permission android:name="android.permission.CAMERA" />在您的 list 中声明,您需要在启动前获得许可,否则 java.lang.SecurityException: Permission Denial

关于android - ActivityResultContracts.TakePicture(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61941959/

相关文章:

java - 点击监听器的Android GridView 获取所选项目

android - 使用可见软件键盘的 Activity

android - 迁移到 Jetpack/AndroidX 后出现 InflateException

android - 如何在视频上设置媒体 Controller ?

android - Google Maps API 街道坐标

Android检查nfc标签是否在附近

android - 在全局流程中服务而不是被创造

Android Q后台限制

android - 无法应用 AppCompatActivity 中的 setSupportActionBar (androidx.appcompat.widget.Toolbar)

android - 包含对 AndroidX 和旧支持库的引用