Thursday, July 4, 2013

Using Intent.ACTION_PICK

One of the best thing about Android is the seamless integration of applications and content providers as if they belong to the same unit. Say I want to let the user customize my application by changing the background  image. Do I need to implement an activity that lists all the images in the device memory and let user pick?
No. The inbuilt Gallery application already does that. All we need is to pick an image from the Gallery application. But how does my application access another application?
Thats where Intent.ACTION_PICK comes to rescue.The predefined intent action Intent.ACTION_PICK helps you to pick an item from a data source. All we need is to know the URI of the provider. Almost all core android applications (eg. Messaging, Gallery, Contacts etc) provide this facility. All you need is the URI of the data you need and required permissions to access that data. 



  1. Pick an Image:

Here we will learn how to pick an image from the gallery.

Code:

public class ActionPickDemo extends Activity {

       protected static final int REQUEST_PICK_IMAGE = 1;
       protected static final int REQUEST_PICK_CROP_IMAGE = 2;
       private Button mPickImageButton;
       private Button mPickCropImageButton;
       private ImageView mImageView;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              // TODO Auto-generated method stub
              super.onCreate(savedInstanceState);
              setContentView(R.layout.action_pick_demo);

              mImageView = (ImageView) findViewById(R.id.image);
              mPickImageButton = (Button) findViewById(R.id.pick_image_button);
              mPickCropImageButton = (Button findViewById(R.id.pick_crop_image_button);
              mPickImageButton.setOnClickListener(mButtonListener);
              mPickCropImageButton.setOnClickListener(mButtonListener);
       }

       private View.OnClickListener mButtonListener = new View.OnClickListener() {

              @Override
              public void onClick(View v) {
                     switch (v.getId()) {

                     case R.id.pick_image_button:
                           Intent pickImageIntent = new Intent(
                                         Intent.ACTION_PICK,                                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                           startActivityForResult(pickImageIntent, REQUEST_PICK_IMAGE);
                           break;
                     case R.id.pick_crop_image_button:
                           String status = Environment.getExternalStorageState();
                           if (status.equals(Environment.MEDIA_MOUNTED)) {
                                  File tempFile = new File(                                            Environment.getExternalStorageDirectory() + "/temp.jpg");
                                  Uri tempUri = Uri.fromFile(tempFile);
                                  Intent pickCropImageIntent = new Intent(
                                                Intent.ACTION_PICK,                                           android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                  pickCropImageIntent.setType("image/*");
                                  pickCropImageIntent.putExtra("crop", "true");
                                  pickCropImageIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                                tempUri);
                                   pickCropImageIntent.putExtra("outputFormat",
                                                Bitmap.CompressFormat.JPEG.toString());
                                  startActivityForResult(pickCropImageIntent,
                                                REQUEST_PICK_CROP_IMAGE);
                           }else{
                                 
                           }
                           break;
                     }
              }
       };

       protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
              switch (requestCode) {

              case REQUEST_PICK_IMAGE:
                     if (RESULT_OK == resultCode) {
                           Uri imageUri = intent.getData();
                           Bitmap bitmap;
                           try {
                                  bitmap = MediaStore.Images.Media.getBitmap(
                                                getContentResolver(), imageUri);
                                  mImageView.setImageBitmap(bitmap);
                           } catch (FileNotFoundException e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
                           } catch (IOException e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
                           }

                     }
                     break;
              case REQUEST_PICK_CROP_IMAGE:
                     Bitmap selectedImage = BitmapFactory.decodeFile(Environment
                                  .getExternalStorageDirectory() + "/temp.jpg");
                     mImageView.setImageBitmap(selectedImage);
                     break;
              }
       }
}

Explanation: 

First we need an Intent with action Intent.ACTION_PICK and Content URI of the Gallery.


Intent pickImageIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickImageIntent, REQUEST_PICK_IMAGE);
Once the user selects an image from the gallery, the URI of the selected image is returned back to our activity via the intent parameter onActivityResult method.


Uri imageUri = intent.getData();


which you can then use to say display the selected image in an ImageView.



Bitmap bitmap;

try {
       bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUri);
       mImageView.setImageBitmap(bitmap);
catch (FileNotFoundException e) {
       e.printStackTrace();
catch (IOException e) {
       e.printStackTrace();
}
Additionally you may want the user to be able to crop the selected image, say for a display image. You may do that easily using some extra parameters with the above intent.



String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED)) {
    File tempFile = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
    Uri tempUri = Uri.fromFile(tempFile);
    Intent pickCropImageIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    pickCropImageIntent.setType("image/*");
    pickCropImageIntent.putExtra("crop""true");
    pickCropImageIntent.putExtra(MediaStore.EXTRA_OUTPUT,tempUri);
    pickCropImageIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    startActivityForResult(pickCropImageIntent, REQUEST_PICK_CROP_IMAGE);
}

In this case, we need to specify the contentType, set flag crop to true, specify the output format of the cropped image and provide a URI of a file where the cropped image will be saved. Thus we first need to check if the device has an external storage mounted.
This time, rather than using the URI from the intent in onActivityResult, we use the generated file directly.

Bitmap selectedImage = BitmapFactory.decodeFile( Environment.getExternalStorageDirectory() +"/temp.jpg");
mImageView.setImageBitmap(selectedImage);
Thats all about picking an image from the gallery for now. We'll continue with more uses of Intent.ACTION_PICK.

2.   Pick an Audio file:

Similar to image, to pick an audio file all you need is

Intent pickAudioIntent = new Intent(Intent.ACTION_PICK,                                         android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);

You receive the selected audio track as a URI via the intent in onActivityResult.

Uri audioUri = intent.getData();

3.   Pick an Video file:

As yo may have already guessed, to pick a video you need

Intent pickVideoIntent = new Intent(Intent.ACTION_PICK,                                         android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);

You receive the selected video file as a URI via the intent in onActivityResult.

Uri videoUri = intent.getData();


4. Pick a Contact:


The intent for this purpose will be

Intent pickContactIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);startActivityForResult(pickContactIntent,REQUEST_PICK_CONTACT);

 This will display a list of all the contacts in the device to pick from.
In onActivityResult, you can fetch the selected Contact URI from the intent.

Uri contactUri = intent.getData();

You can also fetch the selected Contact name from intent extras.

String contactName = intent.getStringExtra("android.intent.extra.shortcut.NAME");

·        If you need to pick from only contacts with a phone number,
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
Thanks all about Intent.ACTION_PICK for now.

No comments:

Post a Comment