Skip to content
Dmitry edited this page Sep 22, 2017 · 4 revisions

First of all make sure your app have access to camera and external storage. You must have the next permissions in your AndroidManifest file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission-sdk-23 android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Just make new instance of the MediaPicker object from Activity and implement callback interface:

public class MainActivity extends Activity implements MediaPicker.OnMediaListener  {

    MediaPicker mediaPicker;

    @Override protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       mediaPicker = MediaPicker.from(this).to(this);
}

On obtaining the result of a 3-rd party app(Gallery, Camera etc) do the following:

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    mediaPicker.process(requestCode, resultCode, data);
}

Setup

To customize the picked photo you must build a params object:

photoParams = new PhotoParams.Builder()
            .mutable(true)
            .rotate(true)
            .maxSize(1920)
            .adjustTextureSize(true)
            .compression(80)
            .pixelFormat(Bitmap.Config.ARGB_8888)
            .noGalleryError("No Gallery")
            .noCameraError("No Camera")
            .takePhotoError("Take photo error")
            .pickGalleryError("Pick gallery error")
            .build();

NOTE: if you want a photo AS IS, just pass mutable(false) to params builder.

Then lets pick a photo from Camera or Gallery app:

@Override public void onClick(View view) { 

        switch (view.getId()) {
            case R.id.button_pick_gallery:
                mediaPicker.with(photoParams).pick();
                break;

            case R.id.button_pick_camera:
                mediaPicker.with(photoParams).take();
                break;
        }
}

Listeners

To get result from the MediaPicker do not forget show progress and error messages:

@Override public void onPickMediaStateChanged(boolean inProgress) {

    progressBar.setVisibility(inProgress ? View.VISIBLE : View.INVISIBLE);

}

@Override public void onPickMediaResult(@NonNull MediaResult result, @Nullable CharSequence errorMsg) {

    if (errorMsg == null) {
        contentImageView.setImageBitmap(BitmapFactory.decodeFile(result.getPath()));
    } else {
        Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
    }

}

Clone this wiki locally