启动Activity的方法。
private void selectImage(){
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
activityResultLauncher.launch(intent);
}
然后,按如下方式覆盖 onRequestPermissionsResult():
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_STORAGE_PERMISSION && grantResults.length > 0){
if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
selectImage();
}else {
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
}
}
另一种,方法如下:
private void displayResult(){
activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK){
Intent data = result.getData();
if (data != null){
Uri selectedImageUri = data.getData();
if (selectedImageUri != null){
try {
InputStream inputStream = getContentResolver().openInputStream(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
noteBinding.imageNote.setImageBitmap(bitmap);
selectedImagePath = getPathFormatUri(selectedImageUri);
}catch (Exception e){
Toast.makeText(CreateNoteActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}
});
}
返回图像的 url/路径的另一种方法。
private String getPathFormatUri(Uri contentUri){
String filePath;
Cursor cursor = getContentResolver()
.query(contentUri,null,null,null,null);
if (cursor == null){
filePath = contentUri.getPath();
}else {
cursor.moveToFirst();
int index = cursor.getColumnIndex("_data");
filePath = cursor.getString(index);
cursor.close();
}
return filePath;
}