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:org.odk.collect.android.widgets.ImageWebViewWidget.java

public ImageWebViewWidget(Context context, FormEntryPrompt prompt) {
    super(context, prompt);

    mInstanceFolder = Collect.getInstance().getFormController().getInstancePath().getParent();

    TableLayout.LayoutParams params = new TableLayout.LayoutParams();
    params.setMargins(7, 5, 7, 5);//from  w w  w  .j av a  2  s. c o  m

    mErrorTextView = new TextView(context);
    mErrorTextView.setId(QuestionWidget.newUniqueId());
    mErrorTextView.setText("Selected file is not a valid image");

    // setup capture button
    mCaptureButton = new Button(getContext());
    mCaptureButton.setId(QuestionWidget.newUniqueId());
    mCaptureButton.setText(getContext().getString(R.string.capture_image));
    mCaptureButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mCaptureButton.setPadding(20, 20, 20, 20);
    mCaptureButton.setEnabled(!prompt.isReadOnly());
    mCaptureButton.setLayoutParams(params);

    // launch capture intent on click
    mCaptureButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Collect.getInstance().getActivityLogger().logInstanceAction(this, "captureButton", "click",
                    mPrompt.getIndex());
            mErrorTextView.setVisibility(View.GONE);
            Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            // We give the camera an absolute filename/path where to put the
            // picture because of bug:
            // http://code.google.com/p/android/issues/detail?id=1480
            // The bug appears to be fixed in Android 2.0+, but as of feb 2,
            // 2010, G1 phones only run 1.6. Without specifying the path the
            // images returned by the camera in 1.6 (and earlier) are ~1/4
            // the size. boo.

            // if this gets modified, the onActivityResult in
            // FormEntyActivity will also need to be updated.
            Uri tempPath = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider",
                    new File(Collect.TMPFILE_PATH));
            i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, tempPath);
            try {
                Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
                ((Activity) getContext()).startActivityForResult(i, FormEntryActivity.IMAGE_CAPTURE);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(getContext(),
                        getContext().getString(R.string.activity_not_found, "image capture"),
                        Toast.LENGTH_SHORT).show();
                Collect.getInstance().getFormController().setIndexWaitingForData(null);
            }

        }
    });

    // setup chooser button
    mChooseButton = new Button(getContext());
    mChooseButton.setId(QuestionWidget.newUniqueId());
    mChooseButton.setText(getContext().getString(R.string.choose_image));
    mChooseButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mChooseButton.setPadding(20, 20, 20, 20);
    mChooseButton.setEnabled(!prompt.isReadOnly());
    mChooseButton.setLayoutParams(params);

    // launch capture intent on click
    mChooseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Collect.getInstance().getActivityLogger().logInstanceAction(this, "chooseButton", "click",
                    mPrompt.getIndex());
            mErrorTextView.setVisibility(View.GONE);
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.setType("image/*");

            try {
                Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
                ((Activity) getContext()).startActivityForResult(i, FormEntryActivity.IMAGE_CHOOSER);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(getContext(),
                        getContext().getString(R.string.activity_not_found, "choose image"), Toast.LENGTH_SHORT)
                        .show();
                Collect.getInstance().getFormController().setIndexWaitingForData(null);
            }

        }
    });

    // finish complex layout
    LinearLayout answerLayout = new LinearLayout(getContext());
    answerLayout.setOrientation(LinearLayout.VERTICAL);
    answerLayout.addView(mCaptureButton);
    answerLayout.addView(mChooseButton);
    answerLayout.addView(mErrorTextView);

    // and hide the capture and choose button if read-only
    if (prompt.isReadOnly()) {
        mCaptureButton.setVisibility(View.GONE);
        mChooseButton.setVisibility(View.GONE);
    }
    mErrorTextView.setVisibility(View.GONE);

    // retrieve answer from data model and update ui
    mBinaryName = prompt.getAnswerText();

    // Only add the imageView if the user has taken a picture
    if (mBinaryName != null) {
        mImageDisplay = new WebView(getContext());
        mImageDisplay.setId(QuestionWidget.newUniqueId());
        mImageDisplay.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mImageDisplay.getSettings().setBuiltInZoomControls(true);
        mImageDisplay.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
        mImageDisplay.setVisibility(View.VISIBLE);
        mImageDisplay.setLayoutParams(params);

        // HTML is used to display the image.
        String html = "<body>" + constructImageElement() + "</body>";

        mImageDisplay.loadDataWithBaseURL("file:///" + mInstanceFolder + File.separator, html, "text/html",
                "utf-8", "");
        answerLayout.addView(mImageDisplay);
    }
    addAnswerView(answerLayout);
}

From source file:com.mvc.imagepicker.ImagePicker.java

/**
 * Get an Intent which will launch a dialog to pick an image from camera/gallery apps.
 *
 * @param context      context.//from  w ww . j av a2s  .  co  m
 * @param chooserTitle will appear on the picker dialog.
 * @return intent launcher.
 */
public static Intent getPickImageIntent(Context context, String chooserTitle) {
    Intent chooserIntent = null;
    List<Intent> intentList = new ArrayList<>();

    Intent pickIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    intentList = addIntentsToList(context, intentList, pickIntent);

    // Camera action will fail if the app does not have permission, check before adding intent.
    // We only need to add the camera intent if the app does not use the CAMERA permission
    // in the androidmanifest.xml
    // Or if the user has granted access to the camera.
    // See https://developer.android.com/reference/android/provider/MediaStore.html#ACTION_IMAGE_CAPTURE
    if (!appManifestContainsPermission(context, Manifest.permission.CAMERA) || hasCameraAccess(context)) {
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        takePhotoIntent.putExtra("return-data", true);
        takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTemporalFile(context)));
        intentList = addIntentsToList(context, intentList, takePhotoIntent);
    }

    if (intentList.size() > 0) {
        chooserIntent = Intent.createChooser(intentList.remove(intentList.size() - 1), chooserTitle);
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
                intentList.toArray(new Parcelable[intentList.size()]));
    }

    return chooserIntent;
}

From source file:com.narkii.security.info.LicenseInfoFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);

    fileButton = (Button) view.findViewById(R.id.button_add_local);
    captureButton = (Button) view.findViewById(R.id.button_add_capture);
    uploadButton = (Button) view.findViewById(R.id.button_upload);
    previewImage = (ImageView) view.findViewById(R.id.image_preview);
    gridView = (GridView) view.findViewById(R.id.image_uploaded);
    fileName = (EditText) view.findViewById(R.id.text_file_name);

    gridViewAdapter = new GridViewAdapter(getActivity(), null, false);
    gridView.setAdapter(gridViewAdapter);

    captureButton.setOnClickListener(new OnClickListener() {

        @Override/*from w  w w . ja  v  a2 s .c  o m*/
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            fileUri = MediaFileStorage.getOutputMediaFileUri(MediaFileStorage.MEDIA_TYPE_IMAGE);
            Log.d(TAG, fileUri.toString());
            Log.d(TAG, fileUri.getPath());
            i.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
            getParentFragment().startActivityForResult(i, Constants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
        }
    });

    fileButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent();
            intent.setType("*/*"); //("image/*")
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            //FragmentFragmentFragmentFragmentResultFragment
            getParentFragment().startActivityForResult(intent, Constants.CONTENT_GET_ACTIVITY_REQUEST_CODE);
        }
    });
    uploadButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (preBitmap != null && !fileName.getText().toString().equals("")) {
                //
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        DbOperations operations = DbOperations.getInstance(getActivity());
                        ContentValues values = new ContentValues();
                        values.put(Permission.COLUMN_FK_ENTERPRISE_ID,
                                getArguments().getLong("enterpriseId", 0));
                        Log.d(TAG, "storage file:" + fileUri.toString());
                        Log.d(TAG, "storage file:" + fileUri.getPath());
                        values.put(Permission.COLUMN_URL, fileUri.toString());
                        values.put(Permission.COLUMN_CERTIFICATE_NAME, fileName.getText().toString());
                        if (isImage)
                            values.put(Permission.COLUMN_TYPE, 1);
                        else
                            values.put(Permission.COLUMN_TYPE, 2);
                        long result = operations.insert(Permission.TABLE_NAME, values);
                        if (result > 0) {
                            Message msg = new Message();
                            msg.what = Constants.INSERT_UPLOADED_OK_MSG;
                            handler.sendMessage(msg);
                        }
                    }
                }).start();
            } else {
                Toast.makeText(getActivity(), "please select file and input name", Toast.LENGTH_LONG).show();
            }
        }
    });

    long id = getArguments().getLong("enterpriseId", 0);
    Bundle bundle = new Bundle();
    bundle.putLong("id", id);
    getLoaderManager().initLoader(Constants.PERMISSION_IMAGE_ID, bundle, this);
}

From source file:com.royclarkson.springagram.PhotoAddFragment.java

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(getActivity().getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;//from  w  w w  .  j  av  a2 s  .c  o m
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

From source file:com.zhongsou.souyue.ui.webview.CustomWebChromeClient.java

/**
 * /* w ww  . j a v a  2  s  .c  o m*/
 */
private void openCarcme() {
    try {
        imageFileUri = mContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new ContentValues());
        if (imageFileUri != null) {
            Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
            if (Utils.isIntentSafe(mContext, i)) {
                fragment.startActivityForResult(i, REQ_CAMERA);
            } else {
                Toast.makeText(mContext, "", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(mContext, "", Toast.LENGTH_SHORT).show();
        }
    } catch (Exception e) {
        Toast.makeText(mContext, "", Toast.LENGTH_SHORT).show();
    }
}

From source file:com.jigarmjoshi.ReportFragment.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.fragment_report, container, false);

    reportImageView = (ImageView) rootView.findViewById(R.id.reportImageView);
    this.cameraIconBitMap = BitmapFactory.decodeResource(getResources(), R.drawable.cam);

    p1ReportButton = (Button) rootView.findViewById(R.id.buttonReportP1);
    p1ReportButton.setBackgroundColor(Color.RED);
    p1ReportButton.setTextColor(Color.BLACK);

    p2ReportButton = (Button) rootView.findViewById(R.id.buttonReportP2);
    p2ReportButton.setBackgroundColor(Color.rgb(255, 100, 0)); // orange
    p2ReportButton.setTextColor(Color.BLACK);

    p3ReportButton = (Button) rootView.findViewById(R.id.buttonReportP3);
    p3ReportButton.setBackgroundColor(Color.rgb(255, 150, 0));
    p3ReportButton.setTextColor(Color.BLACK);

    reportImageView.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            File newFile = getImageFile();
            try {
                newFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();//from  ww  w .  ja v a 2  s. co m
            }

            Uri outputFileUri = Uri.fromFile(newFile);

            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

            startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
        }
    });

    p1ReportButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            performAction(Utility.P1);
        }

    });

    p2ReportButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            performAction(Utility.P2);
        }
    });

    p3ReportButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            performAction(Utility.P3);
        }
    });
    // Gets the MapView from the XML layout and creates it
    mapView = (MapView) rootView.findViewById(R.id.mapviewReport);
    mapView.onCreate(savedInstanceState);
    // Gets to GoogleMap from the MapView and does initialization stuff
    map = mapView.getMap();
    map.getUiSettings().setMyLocationButtonEnabled(true);
    // map.setMyLocationEnabled(true);
    mapView.refreshDrawableState();

    // Needs to call MapsInitializer before doing any CameraUpdateFactory
    // calls
    try {
        MapsInitializer.initialize(this.getActivity());
    } catch (Exception e) {
        e.printStackTrace();
    }
    Utility.focusAtCurrentLocation(map);
    return rootView;
}

From source file:com.bilibili.boxing.utils.CameraPickerHelper.java

/**
 * start system camera to take a picture
 *
 * @param activity      not null if fragment is null.
 * @param fragment      not null if activity is null.
 * @param subFolderPath a folder in external DCIM,must start with "/".
 *///from   w  w  w. j  a  v a2 s .com
public void startCamera(final Activity activity, final Fragment fragment, final String subFolderPath) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || !takePhotoSecure(activity, fragment, subFolderPath)) {
        FutureTask<Boolean> task = BoxingExecutor.getInstance().runWorker(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                try {
                    // try...try...try
                    Camera camera = Camera.open();
                    camera.release();
                } catch (Exception e) {
                    BoxingLog.d("camera is not available.");
                    return false;
                }
                return true;
            }
        });
        try {
            if (task != null && task.get()) {
                startCameraIntent(activity, fragment, subFolderPath, MediaStore.ACTION_IMAGE_CAPTURE,
                        REQ_CODE_CAMERA);
            } else {
                callbackError();
            }
        } catch (InterruptedException | ExecutionException ignore) {
            callbackError();
        }

    }
}

From source file:org.intakers.intake.helper.SelectImageActivity.java

public void takePhoto(View view) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (intent.resolveActivity(getPackageManager()) != null) {
        // Save the photo taken to a temporary file.
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        try {// ww w  . ja  v  a  2s .  co m
            File file = File.createTempFile("IMG_", ".jpg", storageDir);
            mUriPhotoTaken = Uri.fromFile(file);
            //mUriPhotoTaken = FileProvider.getUriForFile(SelectImageActivity.this, BuildConfig.APPLICATION_ID + ".provider", file);
            Log.d("FileName in TakePhoto", file.getAbsolutePath());
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mUriPhotoTaken);
            startActivityForResult(intent, REQUEST_TAKE_PHOTO);
        } catch (IOException e) {
            setInfo(e.getMessage());
        }
    }
}

From source file:com.example.android.emojify.MainActivity.java

/**
 * Creates a temporary image file and captures a picture to store in it.
 *//*w  ww  . j  a  v  a 2 s. c  o m*/
private void launchCamera() {

    // Create the capture image intent
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the temporary File where the photo should go
        File photoFile = null;
        try {
            photoFile = BitmapUtils.createTempImageFile(this);
        } catch (IOException ex) {
            // Error occurred while creating the File
            ex.printStackTrace();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {

            // Get the path of the temporary file
            mTempPhotoPath = photoFile.getAbsolutePath();

            // Get the content URI for the image file
            Uri photoURI = FileProvider.getUriForFile(this, FILE_PROVIDER_AUTHORITY, photoFile);

            // Add the URI so the camera can store the image
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

            // Launch the camera activity
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
}

From source file:org.opendatakit.survey.android.activities.MediaCaptureImageActivity.java

@Override
protected void onResume() {
    super.onResume();

    if (afterResult) {
        // this occurs if we re-orient the phone during the save-recording
        // action
        returnResult();/*from   w w  w. j a va  2 s .com*/
    } else if (!hasLaunched && !afterResult) {
        Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        // workaround for image capture bug
        // create an empty file and pass filename to Camera app.
        if (uriFragmentToMedia == null) {
            uriFragmentToMedia = uriFragmentNewFileBase + TMP_EXTENSION;
        }
        // to make the name unique...
        File mediaFile = ODKFileUtils.getAsFile(appName, uriFragmentToMedia);
        if (!mediaFile.exists()) {
            boolean success = false;
            String errorString = " Could not create: " + mediaFile.getAbsolutePath();
            try {
                success = (mediaFile.getParentFile().exists() || mediaFile.getParentFile().mkdirs())
                        && mediaFile.createNewFile();
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
                errorString = e.toString();
            } finally {
                if (!success) {
                    String err = getString(R.string.media_save_failed);
                    WebLogger.getLogger(appName).e(t, err + errorString);
                    deleteMedia();
                    Toast.makeText(this, err, Toast.LENGTH_SHORT).show();
                    setResult(Activity.RESULT_CANCELED);
                    finish();
                    return;
                }
            }
        }
        i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(mediaFile));

        try {
            hasLaunched = true;
            startActivityForResult(i, ACTION_CODE);
        } catch (ActivityNotFoundException e) {
            String err = getString(R.string.activity_not_found,
                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            WebLogger.getLogger(appName).e(t, err);
            deleteMedia();
            Toast.makeText(this, err, Toast.LENGTH_SHORT).show();
            setResult(Activity.RESULT_CANCELED);
            finish();
        }
    }
}