简体   繁体   English

ACTION_GET_CONTENT 获取图像返回 null URI

[英]ACTION_GET_CONTENT to get image returns null URI

I have an published app that uses an ACTION_GET_CONTENT intent to let the user select one of his/her pictures.我有一个已发布的应用程序,它使用ACTION_GET_CONTENT意图让用户 select 他/她的一张照片。 Here's the code that launches the intent:这是启动意图的代码:

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);

And here's the onActivityResult:这是 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);
}

The problem here is that, on some devices, uri is null even though the user has selected an image.这里的问题是,在某些设备上,即使用户选择了图像, uri也是 null。 Mostly Samsung devices and also some Motorola phones.主要是三星设备和一些摩托罗拉手机。 I also tried with ACTION_PICK instead of ACTION_CONTENT , but it happenned too in some other devices.我也尝试使用ACTION_PICK而不是ACTION_CONTENT ,但它也发生在其他一些设备中。 So I would like to know if there's a way to let the user pick a picture that is universal.所以我想知道是否有办法让用户选择一张通用的图片。

Some phones that suffer this issue are:一些遭受此问题的手机是:

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

Some of the users of these affected devices are notifying that it happens only sometimes.这些受影响设备的一些用户通知说它只是偶尔发生。

OnActivityResult deprecated OnActivityResult 已弃用

Try the new way尝试新方法

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) {
            
        }
    });

}

Try this solution试试这个解决方案

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM