从Android Intent打开图库应用程序

30

我正在寻找一种从意图中打开 Android 相册应用程序的方法。

我不想返回图片,而只是想打开相册,让用户可以像从启动器中选择它一样使用它(查看图片/文件夹)。

我已经尝试了以下操作:

Intent intent = new Intent();  
intent.setAction(android.content.Intent.ACTION_GET_CONTENT);  
intent.setType("image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

然而,这会导致应用在我选择图片后关闭(我知道这是由于 ACTION_GET_CONTENT),但我只需要打开相册。

任何帮助都将不胜感激。

谢谢。


这应该能回答你的问题... http://stackoverflow.com/a/4979492/1620738 - UpLate
你的minSdkVersion版本是多少? - ozbek
6个回答

39

这是你需要的内容:

ACTION_VIEW

将您的代码更改为:

Intent intent = new Intent();  
intent.setAction(android.content.Intent.ACTION_VIEW);  
intent.setType("image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

8
这是唯一回答问题的答案!他只需要打开画廊,不要选择或返回任何东西。 - Enoobong
1
这个答案正是我在寻找的,我也在我的一个应用程序中实现了相同的代码,但它在一些设备上崩溃了 :-( - Akshay Katariya
2
请问如何使用此意图打开相册中的图片文件夹?能否帮我一下? - Vishal Patoliya ツ

34

我希望这会对你有帮助。这段代码对我很有效。

Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
 startActivityForResult(i, RESULT_LOAD_IMAGE);

ResultCode 用于将所选图像更新到画廊视图中。

if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
            && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);

        if (cursor == null || cursor.getCount() < 1) {
            return; // no cursor or no record. DO YOUR ERROR HANDLING
        }

        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

        if(columnIndex < 0) // no column index
            return; // DO YOUR ERROR HANDLING

        String picturePath = cursor.getString(columnIndex);

        cursor.close(); // close cursor

        photo = decodeFilePath(picturePath.toString());

        List<Bitmap> bitmap = new ArrayList<Bitmap>();
        bitmap.add(photo);
        ImageAdapter imageAdapter = new ImageAdapter(
                AddIncidentScreen.this, bitmap);
        imageAdapter.notifyDataSetChanged();
        newTagImage.setAdapter(imageAdapter);
    }

1
游标不应该关闭吗? - Denys Kniazhev-Support Ukraine
在我的情况下(Android 7.0),picturePath为空。 - Makalele
无法导入decodeFilePath()。改用BitmapFactory.decodeFile(pathname)。 - nb2998

17

您可以使用以下意图打开相册:

public static final int RESULT_GALLERY = 0;

Intent galleryIntent = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent , RESULT_GALLERY );

如果你想获得结果URI或者进行其他操作,请使用以下内容:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
    case QuestionEntryView.RESULT_GALLERY :
        if (null != data) {
            imageUri = data.getData();
            //Do whatever that you desire here. or leave this blank

        }
        break;
    default:
        break;
    }
}

在Android 4.0及以上版本测试通过


非常感谢您的帮助 :) - Rohit Kumar

7
  1. Following can be used in Activity or Fragment.

     private File mCurrentPhoto;
    
  2. Add permissions

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"  />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" />
    
  3. Add Intents to open "image-selector" and "photo-capture"

    //A system-based view to select photos.
    private void dispatchPhotoSelectionIntent() {
    Intent galleryIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    this.startActivityForResult(galleryIntent, REQUEST_IMAGE_SELECTOR);
    }
    
    
    
        //Open system camera application to capture a photo.
        private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(App.Instance.getPackageManager()) != null) {
        try {
            createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
        }
        // Continue only if the File was successfully created
        if (mCurrentPhoto != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCurrentPhoto));
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
    }
    
  4. Add handling when getting photo.

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case REQUEST_IMAGE_SELECTOR:
        if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = App.Instance.getContentResolver().query(data.getData(), filePathColumn, null, null, null);
            if (cursor == null || cursor.getCount() < 1) {
                mCurrentPhoto = null;
                break;
            }
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            if(columnIndex < 0) { // no column index
                mCurrentPhoto = null;
                break;
            }
            mCurrentPhoto = new File(cursor.getString(columnIndex));
            cursor.close();
        } else {
            mCurrentPhoto = null;
        }
        break;
    case REQUEST_IMAGE_CAPTURE:
        if (resultCode != Activity.RESULT_OK) {
            mCurrentPhoto = null;
        }
        break;
    }
    if (mCurrentPhoto != null) {
        ImageView imageView = (ImageView) [parent].findViewById(R.id.loaded_iv);
        Picasso.with(App.Instance).load(mCurrentPhoto).into(imageView);
    }
    super.onActivityResult(requestCode, resultCode, data);
    }
    

1
打开相册真的需要权限吗?我打开相册时没有使用任何权限。 - Ishara Amarasekera
@IsharaAmarasekera 如果没有崩溃并且一切正常,那么就不会有问题。 - TeeTracker

5

如果你不想返回结果,请尝试以下简单代码。

Intent i=new Intent(Intent.ACTION_PICK);
            i.setType("image/*");
            startActivity(i);

0
如果有人在添加了以下代码后仍然遇到错误:

Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);

你可能在另一个类中打开了intent(通过调用),因此当你点击按钮时,应用程序会崩溃。

问题的解决方法

将intent放置在与按钮布局文件相连接的类文件中。 例如- activity_main.xml包含一个按钮,并且它连接到MainActivity.java文件。 但由于分段,你正在某个其他类中定义intent(假设是Activity.java),那么除非你将intent放置在MainActivity.java文件中,否则你的应用程序将崩溃。我曾经遇到过这个错误,但通过这种方法解决了它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接