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:mgks.os.webview.MainActivity.java

@SuppressLint({ "SetJavaScriptEnabled", "WrongViewCast" })
@Override//from  ww  w. j a  v a 2s  . c o  m
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.w("READ_PERM = ", Manifest.permission.READ_EXTERNAL_STORAGE);
    Log.w("WRITE_PERM = ", Manifest.permission.WRITE_EXTERNAL_STORAGE);
    //Prevent the app from being started again when it is still alive in the background
    if (!isTaskRoot()) {
        finish();
        return;
    }

    setContentView(R.layout.activity_main);

    asw_view = findViewById(R.id.msw_view);

    final SwipeRefreshLayout pullfresh = findViewById(R.id.pullfresh);
    if (ASWP_PULLFRESH) {
        pullfresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pull_fresh();
                pullfresh.setRefreshing(false);
            }
        });
        asw_view.getViewTreeObserver()
                .addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
                    @Override
                    public void onScrollChanged() {
                        if (asw_view.getScrollY() == 0) {
                            pullfresh.setEnabled(true);
                        } else {
                            pullfresh.setEnabled(false);
                        }
                    }
                });
    } else {
        pullfresh.setRefreshing(false);
        pullfresh.setEnabled(false);
    }

    if (ASWP_PBAR) {
        asw_progress = findViewById(R.id.msw_progress);
    } else {
        findViewById(R.id.msw_progress).setVisibility(View.GONE);
    }
    asw_loading_text = findViewById(R.id.msw_loading_text);
    Handler handler = new Handler();

    //Launching app rating request
    if (ASWP_RATINGS) {
        handler.postDelayed(new Runnable() {
            public void run() {
                get_rating();
            }
        }, 1000 * 60); //running request after few moments
    }

    //Getting basic device information
    get_info();

    //Getting GPS location of device if given permission
    if (ASWP_LOCATION && !check_permission(1)) {
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, loc_perm);
    }
    get_location();

    //Webview settings; defaults are customized for best performance
    WebSettings webSettings = asw_view.getSettings();

    if (!ASWP_OFFLINE) {
        webSettings.setJavaScriptEnabled(ASWP_JSCRIPT);
    }
    webSettings.setSaveFormData(ASWP_SFORM);
    webSettings.setSupportZoom(ASWP_ZOOM);
    webSettings.setGeolocationEnabled(ASWP_LOCATION);
    webSettings.setAllowFileAccess(true);
    webSettings.setAllowFileAccessFromFileURLs(true);
    webSettings.setAllowUniversalAccessFromFileURLs(true);
    webSettings.setUseWideViewPort(true);
    webSettings.setDomStorageEnabled(true);

    asw_view.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            return true;
        }
    });
    asw_view.setHapticFeedbackEnabled(false);

    asw_view.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType,
                long contentLength) {

            if (!check_permission(2)) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[] {
                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE },
                        file_perm);
            } else {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

                request.setMimeType(mimeType);
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie", cookies);
                request.addRequestHeader("User-Agent", userAgent);
                request.setDescription(getString(R.string.dl_downloading));
                request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                        URLUtil.guessFileName(url, contentDisposition, mimeType));
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                assert dm != null;
                dm.enqueue(request);
                Toast.makeText(getApplicationContext(), getString(R.string.dl_downloading2), Toast.LENGTH_LONG)
                        .show();
            }
        }
    });

    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
        asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    } else if (Build.VERSION.SDK_INT >= 19) {
        asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }
    asw_view.setVerticalScrollBarEnabled(false);
    asw_view.setWebViewClient(new Callback());

    //Rendering the default URL
    aswm_view(ASWV_URL, false);

    asw_view.setWebChromeClient(new WebChromeClient() {
        //Handling input[type="file"] requests for android API 16+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            if (ASWP_FUPLOAD) {
                asw_file_message = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType(ASWV_F_TYPE);
                if (ASWP_MULFILE) {
                    i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                }
                startActivityForResult(Intent.createChooser(i, getString(R.string.fl_chooser)), asw_file_req);
            }
        }

        //Handling input[type="file"] requests for android API 21+
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            if (check_permission(2) && check_permission(3)) {
                if (ASWP_FUPLOAD) {
                    if (asw_file_path != null) {
                        asw_file_path.onReceiveValue(null);
                    }
                    asw_file_path = filePathCallback;
                    Intent takePictureIntent = null;
                    if (ASWP_CAMUPLOAD) {
                        takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
                            File photoFile = null;
                            try {
                                photoFile = create_image();
                                takePictureIntent.putExtra("PhotoPath", asw_cam_message);
                            } catch (IOException ex) {
                                Log.e(TAG, "Image file creation failed", ex);
                            }
                            if (photoFile != null) {
                                asw_cam_message = "file:" + photoFile.getAbsolutePath();
                                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                            } else {
                                takePictureIntent = null;
                            }
                        }
                    }
                    Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    if (!ASWP_ONLYCAM) {
                        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                        contentSelectionIntent.setType(ASWV_F_TYPE);
                        if (ASWP_MULFILE) {
                            contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                        }
                    }
                    Intent[] intentArray;
                    if (takePictureIntent != null) {
                        intentArray = new Intent[] { takePictureIntent };
                    } else {
                        intentArray = new Intent[0];
                    }

                    Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                    chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                    chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.fl_chooser));
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                    startActivityForResult(chooserIntent, asw_file_req);
                }
                return true;
            } else {
                get_file();
                return false;
            }
        }

        //Getting webview rendering progress
        @Override
        public void onProgressChanged(WebView view, int p) {
            if (ASWP_PBAR) {
                asw_progress.setProgress(p);
                if (p == 100) {
                    asw_progress.setProgress(0);
                }
            }
        }

        // overload the geoLocations permissions prompt to always allow instantly as app permission was granted previously
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            if (Build.VERSION.SDK_INT < 23 || check_permission(1)) {
                // location permissions were granted previously so auto-approve
                callback.invoke(origin, true, false);
            } else {
                // location permissions not granted so request them
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, loc_perm);
            }
        }
    });
    if (getIntent().getData() != null) {
        String path = getIntent().getDataString();
        /*
        If you want to check or use specific directories or schemes or hosts
                
        Uri data        = getIntent().getData();
        String scheme   = data.getScheme();
        String host     = data.getHost();
        List<String> pr = data.getPathSegments();
        String param1   = pr.get(0);
        */
        aswm_view(path, false);
    }
}

From source file:com.ratebeer.android.gui.fragments.BeerViewFragment.java

public void onStartPhotoSnapping() {
    // Start an intent to snap a picture
    // http://stackoverflow.com/questions/1910608/android-action-image-capture-intent
    try {//from  w w  w . j  a va2  s  .c o m
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            File file = new File(
                    RateBeerForAndroid.DEFAULT_FILES_DIR + "/photos/" + Integer.toString(beerId) + ".jpg");
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }

            Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
            startActivityForResult(i, ACTIVITY_CAMERA);

        } else {
            publishException(null, getString(R.string.error_nocamera));
        }
    } catch (Exception e) {
        publishException(null, getString(R.string.error_nocamera));
    }
}

From source file:com.dycode.jepretstory.mediachooser.activity.HomeFragmentActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int itemID = item.getItemId();
    if (itemID == android.R.id.home) {
        materialMenu.animateTouch();/*from  w  w w.j  a  v a2 s .co m*/
        finish();
    } else if (itemID == R.id.menuNext) {

        //android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();

        if (mVideoFragment != null || mImageFragment != null) {

            if (mVideoFragment != null) {
                if (mVideoFragment.getSelectedVideos() != null
                        && mVideoFragment.getSelectedVideos().size() > 0) {
                    Intent videoIntent = new Intent();
                    videoIntent.setAction(MediaChooser.VIDEO_SELECTED_ACTION_FROM_MEDIA_CHOOSER);
                    //videoIntent.putStringArrayListExtra("list", mVideoFragment.getSelectedVideoList());
                    videoIntent.putParcelableArrayListExtra("selectedVideos",
                            mVideoFragment.getSelectedVideos());
                    setResult(RESULT_OK, videoIntent);
                    sendBroadcast(videoIntent);
                }
            }

            if (mImageFragment != null) {
                if (mImageFragment.getSelectedImages() != null
                        && mImageFragment.getSelectedImages().size() > 0) {
                    Intent imageIntent = new Intent();
                    imageIntent.setAction(MediaChooser.IMAGE_SELECTED_ACTION_FROM_MEDIA_CHOOSER);
                    //imageIntent.putStringArrayListExtra("list", mImageFragment.getSelectedImageList());
                    imageIntent.putParcelableArrayListExtra("selectedImages",
                            mImageFragment.getSelectedImages());
                    setResult(RESULT_OK, imageIntent);
                    sendBroadcast(imageIntent);
                }
            }

            finish();

        } else {
            Toast.makeText(HomeFragmentActivity.this, getString(R.string.plaese_select_file),
                    Toast.LENGTH_SHORT).show();
        }
    } else if (itemID == R.id.menuCamera) {

        if (currentMediaMode == MediaType.VIDEO) {

            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            fileUri = getOutputMediaFileUri(MediaType.VIDEO); // create a file to save the image
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
            Long limit = Long.valueOf((MediaChooserConstants.SELECTED_VIDEO_SIZE_IN_MB * 1024 * 1024));
            intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, limit);
            intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT,
                    MediaChooserConstants.VIDEO_DURATION_LIMIT_IN_SECOND);

            // start the image capture Intent
            startActivityForResult(intent, MediaChooserConstants.CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);

        } else {

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            fileUri = getOutputMediaFileUri(MediaType.IMAGE); // create a file to save the image
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name            

            // start the image capture Intent
            startActivityForResult(intent, MediaChooserConstants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
        }

    }

    return super.onOptionsItemSelected(item);
}

From source file:de.enlightened.peris.ProfileFragment.java

protected boolean canHandleCameraIntent() {
    final Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    final List<ResolveInfo> results = this.activity.getPackageManager().queryIntentActivities(intent, 0);
    return results.size() > 0;
}

From source file:com.nanostuffs.yurdriver.fragment.VehicalRegistration.java

private void takePhotoFromCamera(int code) {

    vehflag = 2;//from   w w  w  .ja va  2s  .  c o m
    Calendar cal = Calendar.getInstance();
    File file = new File(Environment.getExternalStorageDirectory(), (cal.getTimeInMillis() + ".jpg"));

    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {

        file.delete();
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    uri = Uri.fromFile(file);
    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    registerActivity.startActivityForResult(cameraIntent, code, AndyConstants.REGISTER_FRAGMENT_TAG);
}

From source file:no.ntnu.idi.socialhitchhiking.myAccount.MyAccountCar.java

/**
 * Displaying the car information in the layout.
 * @param res/*from   w  ww . j  a  va2s.  co  m*/
 */
public void showMain(CarResponse res, PreferenceResponse prefResInit) {
    // Initializing the views
    setContentView(R.layout.my_account_car);
    this.imageView = (ImageView) this.findViewById(R.id.cameraView);
    carName = (EditText) this.findViewById(R.id.carName);
    bar = (RatingBar) this.findViewById(R.id.ratingBar1);
    seatsText = (EditText) this.findViewById(R.id.myAccountCarSeats);

    // Setting the number of seats available
    prefRes = prefResInit;
    seatsAvailable = prefRes.getPreferences().getSeatsAvailable();
    if (seatsAvailable > 0) {
        seatsText.setText(seatsAvailable.toString());
    } else {
        seatsText.setText("");
    }

    // If the user does have a car registered
    if (user.getCarId() != 0) {
        // Setting the car name
        carNameString = res.getCar().getCarName();
        // Setting the car ID
        id = res.getCar().getCarId();
        // Setting the comfort
        comfort = (float) res.getCar().getComfort();
        // Getting the car image
        byteArray = res.getCar().getPhoto();

        /*Values of the car from database*/

        // Display these values to the user
        carName.setText(carNameString);
        bar.setRating(comfort);

        String empty = "No car type set";
        byteArrayx = empty.getBytes();
        // If a new image is set, display it
        if (byteArray.length > 15) {
            if (!(res.getCar().getPhotoAsBase64().equals(Base64.encode(byteArrayx, Base64.URL_SAFE)))) {
                btm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
                imageView.setImageBitmap(btm);
            }
        }
        // Indicates that the car is initialized
        isCarInitialized = true;
    }
    //if user does not yet have a car registated
    else {
        carNameString = "";
        id = -1;
        comfort = 0.0f;
        String empty = "No car type set";
        byteArray = empty.getBytes();
    }

    // Setting the button for taking a car picture
    Button photoButton = (Button) this.findViewById(R.id.cameraButton);
    photoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            carChanged = true;
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, "tempName");
            cameraIntent.putExtra("return-data", true);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
        }
    });
    // Setting the button for getting a car picture from the phone
    Button getimageButton = (Button) this.findViewById(R.id.getimageButton);
    getimageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            carChanged = true;
            Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, ALBUM_REQUEST);
        }
    });
}

From source file:com.cattle.fragments.UserPhotosFragment.java

/**
 * /*from w  w  w  . j ava  2 s.c  o m*/
 */
private void takePhoto() {
    if (null == mPhotoFile) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mPhotoFile = Utils.getCameraPhotoFile();
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile));
        startActivityForResult(takePictureIntent, RESULT_CAMERA);
    }
}

From source file:br.com.anteros.vendas.gui.AnexoCadastroActivity.java

/**
 * Inicia a cmera para captura da imagem de anexo.
 *///from w ww  .  j  a  va2 s  .c  o  m
private void iniciaCamera() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
    startActivityForResult(takePictureIntent, TIRAR_FOTO);
}

From source file:net.bither.fragment.hot.OptionHotFragment.java

@Override
public void avatarFromCamera() {
    if (FileUtil.existSdCardMounted()) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = ImageFileUtil.getImageForGallery(System.currentTimeMillis());
        imageUri = Uri.fromFile(file);// ww w  .ja v a  2s  . c  o  m
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, BitherSetting.REQUEST_CODE_CAMERA);
    } else {
        DropdownMessage.showDropdownMessage(getActivity(), R.string.no_sd_card);
    }
}

From source file:com.raspi.chatapp.ui.chatting.ChatActivity.java

public void sendCameraImage(View view) {
    // hide the popup
    View v = findViewById(R.id.popup_layout);
    if (v != null) {
        v.setVisibility(View.GONE);
        attachPopup = false;/*from   www .j  a v a2s .c o m*/
    }
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    Uri fileUri = Uri.fromFile(MyFileUtils.getFileName());
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
    startActivityForResult(cameraIntent, SEND_CAMERA_IMAGE_REQUEST_CODE);
}