获取图像的ACTION_GET_CONTENT返回空URI

问题描述 投票:0回答:3

我有一个已发布的应用程序,它使用

ACTION_GET_CONTENT
意图让用户选择他/她的一张照片。这是启动意图的代码:

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
intent.putExtra(Intent.CATEGORY_OPENABLE, true);
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_pic)), SELECT_IMAGE);

这是 onActivityResult:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if(resultCode == RESULT_OK) {
        if (requestCode == SELECT_IMAGE) {
            if (data != null) {
                Uri uri = data.getData();
                ...
                }
            }
        }
    }

    super.onActivityResult(requestCode, resultCode, data);
}

这里的问题是,在某些设备上,即使用户选择了图像,

uri
也为空。主要是三星设备,也有一些摩托罗拉手机。我也尝试过使用
ACTION_PICK
而不是
ACTION_CONTENT
,但在其他一些设备中也发生了这种情况。所以我想知道是否有办法让用户选择一张通用的图片。

遇到此问题的一些手机是:

  • 三星 Galaxy A21S - Android 11 (SDK 30)
  • 三星 Galaxy A3 (2016) - Android 7.0 (SDK 24)
  • 摩托罗拉 moto e6 play - Android 9 (SDK 28)

这些受影响设备的一些用户通知说这种情况只是偶尔发生。

android image android-intent gallery samsung-mobile
3个回答
0
投票

尝试这个解决方案

val getImage = registerForActivityResult(ActivityResultContracts.GetContent()) {
        if (it != null) {
            binding.image.setImageURI(it)
        }
    }
    binding.image.setOnClickListener {
        getImage.launch("image/*")
    }

0
投票

对我来说,活动 launchMode 设置为 singleInstance,因为从图库中选取的图像 uri 返回为 null,改变它就达到了目的。


-1
投票

OnActivityResult 已弃用

尝试新方法

ActivityResultLauncher<String> launcher;

.....

Button pick = findViewById(R.id.pick);
pick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                launcher.launch("image/*");
            }
        });

launcher = registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(Uri result) {
            
        }
    });

}
© www.soinside.com 2019 - 2024. All rights reserved.