Call the system camera to take pictures and obtain the abbreviated picture sketch

When the system camera is called to take a picture, if the path is not passed, the picture is returned to the thumbnail by default, and no permission is required

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) ! = null) { startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); }Copy the code

takePictureIntent.resolveActivity(getPackageManager()) ! = null is described in the official documentation: The startActivityForResult () method is protected by the condition that calls resolveActivity (), which returns the first active component that can handle the intent, and it is important to perform this check, Because if you call startActivityForResult () with an intent that no application can handle, your application will crash. So as long as the result is not empty, it is safe to use the intent, which basically means to check if there is a camera in the phone.


Another way to detect a camera is

<manifest ... >
    <uses-feature android:name="android.hardware.camera"
                  android:required="true" />
    ...
</manifest>
Copy the code

Required =true indicates that the phone must have camera hardware in order to install the app. Otherwise, installation is not allowed


To deal with the callback

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); mImageView.setImageBitmap(imageBitmap); }}Copy the code

Call the system camera to take photos and get full size photos

If you want to save a full-size photo, you must provide a full file name, and when the photo needs to be saved to the public directory, you need a write permission (the write permission already implicitly allows reading [READ_EXTERNAL_STORAGE], Like this app photos can be written to the external storage, the link of the external storage is getExternalStoragePublicDirectory ()

<manifest ... > <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ... </manifest>Copy the code

Use getExternalFilesDir() and getFilesDir() to save photos to private directories. Files in these two directories will be automatically deleted when the application is deleted. Permissions are required under android4.4. Therefore, this permission should only be added below 4.4

<manifest ... > <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" /> ... </manifest>Copy the code
  • Provide a nonconflicting file name, such as by time
String mCurrentPhotoPath;

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
        imageFileName,  /* prefix */
        ".jpg",         /* suffix */
        storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}
Copy the code
  • Construct photo IntEnts for 7.0 and 4.0
static final int REQUEST_TAKE_PHOTO = 1; private void camera2() { 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 File where the photo should go File photoFile = null; try { photoFile = createImageFile(); } catch (IOException ex) { // Error occurred while creating the File } // Continue only if the File was successfully created if (photoFile ! = null) { Uri photoURI = FileProvider.getUriForFile(this, "lsp.com.ipctest.fileprovider", photoFile); List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo resolveInfo : resInfoList) { String packageName = resolveInfo.activityInfo.packageName; grantUriPermission(packageName, photoURI, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); } takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO); }}}Copy the code

FileProvider. GetUriForFile () is used to return a content: / / URI. For newer applications targeting Android 7.0 (API level 24), passing a file through a package boundary: // URI causes FileUriExposedException

Hongyang blog about the processing of photo encapsulation on android7.0 and 4.0 (click to jump)

  • The obtained results
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) { Bitmap imageBitmap = BitmapFactory.decodeFile(mCurrentPhotoPath); Log.e(TAG, "file size" + imagebitmap.getBytecount () / 1024 + "KB "); ((ImageView) findViewById(R.id.img)).setImageBitmap(imageBitmap); }Copy the code
  • Save the photo to the album if you save the photo in the path isgetExternalFilesDir()Media scanner can’t access it, only your own app can, so here’s how to save images to albums
private void galleryAddPic() {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(mCurrentPhotoPath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);
}
Copy the code

Similar to the introduction of a good article recommendation -Android call system camera photography guide (has been adapted Android N)