Example usage for android.provider MediaStore ACTION_IMAGE_CAPTURE

List of usage examples for android.provider MediaStore ACTION_IMAGE_CAPTURE

Introduction

In this page you can find the example usage for android.provider MediaStore ACTION_IMAGE_CAPTURE.

Prototype

String ACTION_IMAGE_CAPTURE

To view the source code for android.provider MediaStore ACTION_IMAGE_CAPTURE.

Click Source Link

Document

Standard Intent action that can be sent to have the camera application capture an image and return it.

Usage

From source file:com.googlecode.android_scripting.facade.CameraFacade.java

@Rpc(description = "Starts the image capture application to take a picture and saves it to the specified path.")
public void cameraInteractiveCapturePicture(@RpcParameter(name = "targetPath") final String targetPath) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File file = new File(targetPath);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
    AndroidFacade facade = mManager.getReceiver(AndroidFacade.class);
    facade.startActivityForResult(intent);
}

From source file:nl.basvanmarwijk.mylocations.viewcontroller.LocationItemDetailFragment.java

private void launchCamera() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    try {//from   ww  w .  j a  v  a 2s . c o m
        pictureUri = ExternalStorageHelper.createUriForNewMediaFile();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);

        startActivityForResult(intent, CAMERA_INTENT_REQUEST_CODE);
    } catch (IOException e) {
        Toast.makeText(getActivity(), R.string.toast_could_not_store_picture, Toast.LENGTH_LONG).show();
    }
}

From source file:com.trail.octo.Identity.java

public void requestCameraPermission() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            Log.e("Check", "Go To Settings");
            Toast.makeText(getApplicationContext(), "OCTO requires this Permission to upload Images!",
                    Toast.LENGTH_LONG).show();
            final Intent i = new Intent();
            i.setAction(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            i.addCategory(Intent.CATEGORY_DEFAULT);
            i.setData(Uri.parse("package:" + Identity.this.getPackageName()));
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            startActivity(i);// Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {/*from  ww  w  . ja  v a2s .c  om*/

            // No explanation needed, we can request the permission.

            Log.e("Check", "Requesting");
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA },
                    REQUEST_CAMERA_PERMISSION);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    } else {
        Log.e("Check", "Already Granted");
        //Already Permission Granted
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 1);
    }
}

From source file:com.mobicage.rogerthat.GroupDetailActivity.java

private void getNewAvatar(boolean checkPermission) {
    T.UI();/*from   w w  w .j  a v a 2 s .  c om*/
    if (checkPermission) {
        final SafeRunnable continueRunnable = new SafeRunnable() {
            @Override
            protected void safeRun() throws Exception {
                getNewAvatar(false);
            }
        };

        final SafeRunnable runnableCheckStorage = new SafeRunnable() {
            @Override
            protected void safeRun() throws Exception {
                if (askPermissionIfNeeded(Manifest.permission.WRITE_EXTERNAL_STORAGE, PERMISSION_REQUEST_CAMERA,
                        continueRunnable, null))
                    return;
                continueRunnable.run();
            }
        };
        if (askPermissionIfNeeded(Manifest.permission.CAMERA, PERMISSION_REQUEST_CAMERA, runnableCheckStorage,
                null))
            return;
        runnableCheckStorage.run();
        return;
    }
    File image;
    try {
        image = getTmpUploadPhotoLocation();
    } catch (IOException e) {
        L.d(e.getMessage());
        UIUtils.showLongToast(getApplicationContext(), e.getMessage());
        return;
    }
    image.delete();
    mUriSavedImage = Uri.fromFile(image);
    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUriSavedImage);
    cameraIntent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());

    Intent galleryIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    galleryIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUriSavedImage);
    galleryIntent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
    galleryIntent.setType("image/*");

    PackageManager pm = getPackageManager();
    final Intent chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.select_source));
    if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { cameraIntent });
    }

    startActivityForResult(chooserIntent, PICK_IMAGE);

}

From source file:es.uja.photofirma.android.CameraActivity.java

/**
 * Se ejecuta al pulsar sobre el boton para abrir la captura de fotos, inicia la captura y almacena la fotografa realizada
 *///from   ww  w  .  ja va  2  s .co m
public void onTakeAPhoto(View view) {
    logger.appendLog(300, "el usuario abre la aplicacion de fotos");

    //Se crea nueva instancia de la clase PhotoMaker() para automatizar el proceso de trabajo con fotografas
    PhotoCapture = new PhotoMaker();
    File imagen = PhotoCapture.savePhoto();
    photoLocation = imagen.getAbsolutePath();

    //Se redirige al usuario a la app de captura de fotografas
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    takePictureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(imagen));
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        //         Toast.makeText(getApplicationContext(), getString(R.string.privacy_alert), Toast.LENGTH_LONG).show();
        startActivityForResult(takePictureIntent, CameraActivity.REQUEST_IMAGE_CAPTURE);
    }
}

From source file:com.support.android.designlibdemo.activities.CampaignDetailActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
    imageUrls = new ArrayList<String>();
    customProgress = (CustomProgress) findViewById(R.id.pbGoal);
    ivCampaignImage = (ImageView) findViewById(R.id.ivCampaighnImage);
    tvCampaignOverview = (TextView) findViewById(R.id.tvCampaignOverview);
    ivArrowDown = (ImageView) findViewById(R.id.ivArrowDown);
    //   tvCampaignText = (TextView) findViewById(R.id.tvCampaignDetails);
    tvGoal = (TextView) findViewById(R.id.tvCampaignGoal);
    btTakeActionRipple = (RippleView) findViewById(R.id.bt_take_an_action_ripple);
    campaign = (Campaign) getIntent().getSerializableExtra(ITENT_TAG);

    if (campaign.getIsSupported()) {
        btTakeActionRipple.setVisibility(View.GONE);
        ivArrowDown.setImageResource(R.drawable.ic_checked);
    } else {//  w  w  w  .  j  a v  a 2  s  . c  o m
        btTakeActionRipple.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
            @Override
            public void onComplete(RippleView rippleView) {
                Intent i = new Intent(CampaignDetailActivity.this, SignPetitionActivity.class);
                i.putExtra(ITENT_TAG, campaign);
                startActivity(i);
            }
        });
    }

    getImagesUploadedByUserForCampaign(campaign.getObjectId());

    final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(false);

    CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);

    collapsingToolbar.setTitle(campaign.getTitle());
    collapsingToolbar.getCollapsedTitleGravity();
    loadBackdrop(campaign.getImageUrl(), ivCampaignImage);

    PrettyText goal = new PrettyText();
    String decimalGoal = "";
    String decimalCount = "";

    //setting up progress bar
    customProgress.setProgressColor(getResources().getColor(R.color.green_500));
    customProgress.setProgressBackgroundColor(getResources().getColor(R.color.green_200));
    customProgress.setMaximumPercentage(calculatePercentage(campaign.getGoal(), campaign.getGoalCount()));
    customProgress.useRoundedRectangleShape(30.0f);
    customProgress.setShowingPercentage(true);
    //set text above progress
    tvCampaignOverview.setText(campaign.getShortDescription());

    expandableTextView = (ExpandableTextView) findViewById(R.id.viewmore);

    expandableTextView.setText(campaign.getLongDescription());

    //  tvCampaignText.setText(campaign.getLongDescription());

    //set goal text
    decimalGoal = goal.addComma(campaign.getGoal()) + " signatures";
    decimalCount = goal.addComma(campaign.getGoalCount());
    tvGoal.setText(decimalCount + " out of " + decimalGoal);

    ivCampaignImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (imageUrls.size() > 0) {
                Intent i = new Intent(CampaignDetailActivity.this, PhotoGalleryActivity.class);
                i.putExtra(ITENT_TAG, campaign.getObjectId());
                i.putStringArrayListExtra(ITENT_TAG, imageUrls);
                startActivity(i);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
            } else {
                buildDialogNoPictures(CampaignDetailActivity.this).show();
            }
        }
    });

    //set floating action button
    floatingCamera = (FloatingActionButton) findViewById(R.id.bt_camera);
    final int[] selection = new int[1];

    floatingCamera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            FragmentManager fm = getSupportFragmentManager();
            final CameraDialog dialog = CameraDialog.newInstance("Add a new picture:");

            dialog.setOnChoiceClickListener(new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    selection[0] = which;
                }
            });

            dialog.setPositiveListener(new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    if (selection[0] == 0) {
                        // create Intent to take a picture and return control to the calling application
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        photoUri = Uri.fromFile(getOutputMediaFile()); // create a file to save the image
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); // set the image file name
                        // Start the image capture intent to take photo
                        startActivityForResult(intent, TAKE_PHOTO_CODE);
                    } else {
                        // Take the user to the gallery app to pick a photo
                        Intent photoGalleryIntent = new Intent(Intent.ACTION_PICK,
                                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(photoGalleryIntent, PICK_PHOTO_CODE);

                    }
                    dialog.dismiss();

                }
            });

            dialog.setCancelClickListener(new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    dialog.dismiss();
                }

            });

            dialog.show(fm, "TAG_DIALOG");

        }

    });

}

From source file:com.demo.firebase.MainActivity.java

@AfterPermissionGranted(RC_STORAGE_PERMS)
private void launchCamera() {
    Log.d(TAG, "launchCamera");

    // Check that we have permission to read images from external storage.
    String perm = Manifest.permission.WRITE_EXTERNAL_STORAGE;
    if (!EasyPermissions.hasPermissions(this, perm)) {
        EasyPermissions.requestPermissions(this, getString(R.string.rationale_storage), RC_STORAGE_PERMS, perm);
        return;/*from   ww w . ja va 2 s.  c  om*/
    }

    // Choose file storage location, must be listed in res/xml/file_paths.xml
    File dir = new File(Environment.getExternalStorageDirectory() + "/photos");
    File file = new File(dir, UUID.randomUUID().toString() + ".jpg");
    try {
        // Create directory if it does not exist.
        if (!dir.exists()) {
            dir.mkdir();
        }
        boolean created = file.createNewFile();
        Log.d(TAG, "file.createNewFile:" + file.getAbsolutePath() + ":" + created);
    } catch (IOException e) {
        Log.e(TAG, "file.createNewFile" + file.getAbsolutePath() + ":FAILED", e);
    }

    // Create content:// URI for file, required since Android N
    // See: https://developer.android.com/reference/android/support/v4/content/FileProvider.html
    mFileUri = FileProvider.getUriForFile(this, "com.google.firebase.quickstart.firebasestorage.fileprovider",
            file);

    // Create and launch the intent
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);

    // Grant permission to camera (this is required on KitKat and below)
    List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(takePictureIntent,
            PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resolveInfos) {
        String packageName = resolveInfo.activityInfo.packageName;
        grantUriPermission(packageName, mFileUri,
                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }

    // Start picture-taking intent
    startActivityForResult(takePictureIntent, RC_TAKE_PICTURE);
}

From source file:com.barak.pix.NewPostActivity.java

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

    if (requestCode == TC_PICK_IMAGE) {
        if (resultCode == RESULT_OK) {
            final boolean isCamera;
            if (data == null || data.getData() == null) {
                isCamera = true;// w ww  .  j a va  2 s .  c  om
            } else {
                isCamera = MediaStore.ACTION_IMAGE_CAPTURE.equals(data.getAction());
            }
            if (!isCamera && data != null) {
                mFileUri = data.getData();
            }
            if (mFileUri != null) {
                mTaskFragment.resizeBitmap(mFileUri, THUMBNAIL_MAX_DIMENSION);
                mTaskFragment.resizeBitmap(mFileUri, FULL_SIZE_MAX_DIMENSION);
            }

        }
    }
}

From source file:de.stadtrallye.rallyesoft.model.pictures.PictureManager.java

/**
 * Get an intent to either take a picture with the camera app or select an app that can pick an existing picture
 *//*from  w ww  .  j a v a2  s  .co  m*/
public Intent startPictureTakeOrSelect(SourceHint sourceHint) {
    //Attention: Our RequestCode will not be used for the result, if a jpeg is picked, data.getType will contain image/jpeg, if the picture was just taken with the camera it will be null
    Intent pickIntent = new Intent();
    pickIntent.setType("image/jpeg");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        pickIntent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        pickIntent.addCategory(Intent.CATEGORY_OPENABLE);
    } else {
        pickIntent.setAction(Intent.ACTION_GET_CONTENT);
    }

    Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    Uri fileUri = getPicturePlaceholderUri(PictureManager.MEDIA_TYPE_IMAGE, sourceHint); // reserve a filename to save the image
    takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
    takePhotoIntent.putExtra("return-data", true);

    Intent chooserIntent = Intent.createChooser(pickIntent, context.getString(R.string.select_take_picture));
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { takePhotoIntent });

    return chooserIntent;
}

From source file:com.khoahuy.phototag.HomeActivity.java

private void dispatchTakePictureIntent(int actionCode) {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File f = null;//from   w  w  w  .  j av a 2s. c  o  m
    try {
        f = setUpPhotoFile();
        // mCurrentPhotoPath = f.getAbsolutePath();
        // takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(f));
    } catch (IOException e) {
        e.printStackTrace();
        f = null;
        mCurrentPhotoPath = null;
    }
    switch (actionCode) {
    case ACTION_TAKE_PHOTO_B:
        // takePictureIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,
        // ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        break;

    default:
        break;
    } // switch

    startActivityForResult(takePictureIntent, actionCode);
}