Get/pick an image from Android's built-in Gallery app programmatically

前端 未结 19 1856
终归单人心
终归单人心 2020-11-22 00:49

I am trying to open an image / picture in the Gallery built-in app from inside my application.

I have a URI of the picture (the picture is located on the SD card).

19条回答
  •  天命终不由人
    2020-11-22 01:01

    Assuming you have an image folder in your SD card directory for images only.

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    // tells your intent to get the contents
    // opens the URI for your image directory on your sdcard
    intent.setType("file:///sdcard/image/*"); 
    startActivityForResult(intent, 1);
    

    Then you can decide with what you would like to do with the content back in your activity.

    This was an example to retrieve the path name for the image, test this with your code just to make sure you can handle the results coming back. You can change the code as needed to better fit your needs.

    protected final void onActivityResult(final int requestCode, final int
                         resultCode, final Intent i) {
        super.onActivityResult(requestCode, resultCode, i);
    
      // this matches the request code in the above call
      if (requestCode == 1) {
          Uri _uri = i.getData();
    
        // this will be null if no image was selected...
        if (_uri != null) {
          // now we get the path to the image file
         cursor = getContentResolver().query(_uri, null,
                                          null, null, null);
         cursor.moveToFirst();
         String imageFilePath = cursor.getString(0);
         cursor.close();
         }
       }
    

    My advice is to try to get retrieving images working correctly, I think the problem is the content of accessing the images on the sdcard. Take a look at Displaying images on sd card.

    If you can get that up and running, probably by the example supplying a correct provider, you should be able to figure out a work-around for your code.

    Keep me updated by updating this question with your progress. Good luck

提交回复
热议问题