当前位置:   article > 正文

【AndroidX】Activity Result API使用示例_resultsuccess = (imageview) findviewbyid(r.id.veri

resultsuccess = (imageview) findviewbyid(r.id.verify_result_sucess);

参考官方链接:获取Activity的结果

  1. implementation 'androidx.activity:activity:1.2.0-beta01'
  2. implementation 'androidx.fragment:fragment:1.3.0-beta01'

本示例演示了从系统相册中获取图片uri并进行显示的功能。

Activity文件:

  1. public class MainActivity extends AppCompatActivity {
  2. public static final String TAG = "ActivityTest";
  3. private static final int GET_IMAGE_REQUEST_CODE = 1;
  4. private ImageView imageView;
  5. // Activity返回结果
  6. private final ActivityResultLauncher<String> mGetContent = registerForActivityResult(
  7. new ActivityResultContracts.GetContent(),
  8. result -> {
  9. displayImage(parseImageUri(result));
  10. }
  11. );
  12. @Override
  13. protected void onCreate(Bundle savedInstanceState) {
  14. super.onCreate(savedInstanceState);
  15. setContentView(R.layout.activity_main);
  16. findViewById(R.id.get_content).setOnClickListener(v -> checkPermission());
  17. imageView = findViewById(R.id.img);
  18. }
  19. @Override
  20. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  21. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  22. if (requestCode == GET_IMAGE_REQUEST_CODE) {
  23. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  24. mGetContent.launch("image/*");
  25. } else {
  26. Toast.makeText(this, "You denied the permission.", Toast.LENGTH_SHORT).show();
  27. }
  28. }
  29. }
  30. // 检查读外部存储权限
  31. private void checkPermission() {
  32. if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
  33. != PackageManager.PERMISSION_GRANTED) {
  34. ActivityCompat.requestPermissions(this, new String[]{
  35. Manifest.permission.READ_EXTERNAL_STORAGE
  36. }, GET_IMAGE_REQUEST_CODE);
  37. } else {
  38. mGetContent.launch("image/*"); // 根据返回结果
  39. }
  40. }
  41. // 解析uri,获取图片真实地址
  42. private String parseImageUri(Uri uri) {
  43. String imagePath = null;
  44. if (DocumentsContract.isDocumentUri(this, uri)) {
  45. String docId = DocumentsContract.getDocumentId(uri);
  46. Log.d(TAG, "docId: " + docId);
  47. if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
  48. String id = docId.split(":")[1];
  49. String selection = MediaStore.Images.Media._ID + "=" + id;
  50. imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
  51. } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
  52. Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.parseLong(docId));
  53. imagePath = getImagePath(contentUri, null);
  54. }
  55. } else if ("content".equalsIgnoreCase(uri.getScheme())) { // content://com.miui.gallery.open/raw/%2Fstorage%2Femulated%2F0%2FDCIM%2FScreenshots%2FScreenshot_2020-10-25-14-43-57-798_com.miui.home.jpg
  56. Log.d(TAG, "is content.");
  57. imagePath = getImagePath(uri, null);
  58. } else if ("file".equalsIgnoreCase(uri.getScheme())) {
  59. Log.d(TAG, "is file.");
  60. imagePath = uri.getPath();
  61. }
  62. Log.d(TAG, "imagePath: " + imagePath);
  63. return imagePath;
  64. }
  65. // 获取真实图片地址
  66. private String getImagePath(Uri uri, String selection) {
  67. String path = null;
  68. Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
  69. if (cursor != null) {
  70. if (cursor.moveToFirst()) {
  71. path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
  72. }
  73. cursor.close();
  74. }
  75. return path;
  76. }
  77. // 显示图片
  78. private void displayImage(String imagePath) {
  79. if (imagePath != null) {
  80. Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
  81. imageView.setImageBitmap(bitmap);
  82. } else {
  83. Toast.makeText(this, "Failed to get image.", Toast.LENGTH_SHORT).show();
  84. }
  85. }
  86. }

使用权限:

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

布局文件:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:orientation="vertical"
  8. tools:context=".MainActivity">
  9. <Button
  10. android:id="@+id/get_content"
  11. android:layout_width="match_parent"
  12. android:layout_height="wrap_content"
  13. android:text="Get Content" />
  14. <ImageView
  15. android:id="@+id/img"
  16. android:layout_gravity="center_horizontal"
  17. android:layout_width="wrap_content"
  18. android:layout_height="wrap_content"/>
  19. </LinearLayout>

 

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号