赞
踩
参考官方链接:获取Activity的结果
- implementation 'androidx.activity:activity:1.2.0-beta01'
- implementation 'androidx.fragment:fragment:1.3.0-beta01'
本示例演示了从系统相册中获取图片uri并进行显示的功能。
Activity文件:
- public class MainActivity extends AppCompatActivity {
-
- public static final String TAG = "ActivityTest";
- private static final int GET_IMAGE_REQUEST_CODE = 1;
-
- private ImageView imageView;
-
- // Activity返回结果
- private final ActivityResultLauncher<String> mGetContent = registerForActivityResult(
- new ActivityResultContracts.GetContent(),
- result -> {
- displayImage(parseImageUri(result));
- }
- );
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- findViewById(R.id.get_content).setOnClickListener(v -> checkPermission());
-
- imageView = findViewById(R.id.img);
- }
-
- @Override
- public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
- super.onRequestPermissionsResult(requestCode, permissions, grantResults);
-
- if (requestCode == GET_IMAGE_REQUEST_CODE) {
- if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- mGetContent.launch("image/*");
- } else {
- Toast.makeText(this, "You denied the permission.", Toast.LENGTH_SHORT).show();
- }
- }
- }
-
- // 检查读外部存储权限
- private void checkPermission() {
- if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
- != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.requestPermissions(this, new String[]{
- Manifest.permission.READ_EXTERNAL_STORAGE
- }, GET_IMAGE_REQUEST_CODE);
- } else {
- mGetContent.launch("image/*"); // 根据返回结果
- }
- }
-
- // 解析uri,获取图片真实地址
- private String parseImageUri(Uri uri) {
- String imagePath = null;
-
- if (DocumentsContract.isDocumentUri(this, uri)) {
- String docId = DocumentsContract.getDocumentId(uri);
- Log.d(TAG, "docId: " + docId);
-
- if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
- String id = docId.split(":")[1];
- String selection = MediaStore.Images.Media._ID + "=" + id;
- imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
- } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
- Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.parseLong(docId));
- imagePath = getImagePath(contentUri, null);
- }
- } 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
- Log.d(TAG, "is content.");
-
- imagePath = getImagePath(uri, null);
- } else if ("file".equalsIgnoreCase(uri.getScheme())) {
- Log.d(TAG, "is file.");
-
- imagePath = uri.getPath();
- }
-
- Log.d(TAG, "imagePath: " + imagePath);
-
- return imagePath;
- }
-
- // 获取真实图片地址
- private String getImagePath(Uri uri, String selection) {
- String path = null;
- Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
- if (cursor != null) {
- if (cursor.moveToFirst()) {
- path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
- }
- cursor.close();
- }
- return path;
- }
-
- // 显示图片
- private void displayImage(String imagePath) {
- if (imagePath != null) {
- Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
- imageView.setImageBitmap(bitmap);
- } else {
- Toast.makeText(this, "Failed to get image.", Toast.LENGTH_SHORT).show();
- }
- }
- }
使用权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
布局文件:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- tools:context=".MainActivity">
-
- <Button
- android:id="@+id/get_content"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Get Content" />
-
- <ImageView
- android:id="@+id/img"
- android:layout_gravity="center_horizontal"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"/>
-
- </LinearLayout>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。