Android---Open the camera to take pictures

Simply open the system camera to take a picture and display it on the UI, which is suitable for switching with the personal homepage avatar.

1. Add permissions. Add permission to use the camera in AndroidManifest.xml.

<uses-permission android:name="android.permission.CAMERA"/>

2. Layout. The layout content is relatively simple. A Button is used to open the camera; an ImageView is used to receive the captured pictures.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_open_gallery"
        android:layout_width="150dp"
        android:layout_height="75dp"
        android:layout_centerHorizontal="true"
        android:text="拍照"
        android:textSize="20sp"/>

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/btn_open_gallery"/>

</RelativeLayout>

3. Dynamically apply for permissions. Google   introduced a permission application mechanism in Android 6.0 . In addition to applying for static permissions in AndroidManifest.xml, you also need to apply dynamically in the code. Here you need to apply for system camera permissions.

    /**
     * 申请动态权限
     */
    private void requestPermission() {
        if (ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CODE);
        }else {
            takePhoto();
        }
    }

4. Callback for requesting permission.

    /**
     * 用户选择是否开启权限操作后的回调;TODO 同意/拒绝
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // TODO 用户同意开启权限,打开相机
                takePhoto();
            }else{
                Log.d("HL", "权限申请拒绝!");
            }
        }
    }

5. Create a file to store the photos you took

    /**
     * 创建一个存放拍的照片的文件
     */
    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault())
                .format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        Log.d("HL", imageFileName);
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(
                imageFileName,  /* prefix */
                ".bmp",         /* suffix */
                storageDir      /* directory */
        );
    }

6. Turn on the camera.

    /**
     * 打开相机,选择头像
     */
    private void takePhoto() {
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        // 确保有一个活动来处理意图
        if (takePhotoIntent.resolveActivity(getPackageManager()) != null) {
            // 创建保存图片的文件夹
            File imageFile = null;
            try {
                imageFile = createImageFile();
            }catch (Exception e){
                e.printStackTrace();
            }
            if (imageFile != null) {
                //TODO imageUri 用来接收拍摄的这张照片的真实路径
                imageUri = FileProvider.getUriForFile(this, "com.example.takePhoto.fileprovider", imageFile);
            }

            takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST_CODE);
        }
    }

7. Result callback. The user takes a picture, receives the returned result and displays it in ImageView.

 @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TAKE_PHOTO_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                try {
                    InputStream inputStream = getContentResolver().openInputStream(imageUri);
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    mImg.setImageBitmap(bitmap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

8. Register content provider (Provider). Register in AndroidManifest.xml.

Among them, the value of the android:name attribute is fixed, and the value of the android:authorities attribute must be consistent with the second parameter in the FileProvider.getUriForFile() method in the takePhoto() method above, and this parameter is fixed to "package name ( com.xxx.xxx).fileprovider". In addition, there is also the internal use of <meta-data> in the <provider> tag to specify the shared path of the Uri, and introduce an @xml/file_paths resource.

Create a File as "file_paths" file under res -> xml and add the following content

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-files-path name="image_path" path="/" />
</paths>

Among them, external-path is used to specify the Uri share, the name attribute can be filled in casually, and the value of the path attribute indicates the specific path of the share.

ManiActivity.java complete code

package com.example.takephoto;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    private static final int PERMISSION_REQUEST_CODE = 0;
    private static final int TAKE_PHOTO_REQUEST_CODE = 0;
    private Uri imageUri;

    private ImageView mImg;
    private Button mTakePhoto;

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

        mImg = findViewById(R.id.img);
        mTakePhoto = findViewById(R.id.btn_take_photo);

        mTakePhoto.setOnClickListener(v -> {
            requestPermission();
        });
    }

    /**
     * 申请动态权限
     */
    private void requestPermission() {
        if (ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CODE);
        }else {
            takePhoto();
        }
    }

    /**
     * 用户选择是否开启权限操作后的回调;TODO 同意/拒绝
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // TODO 用户同意开启权限,打开相机
                takePhoto();
            }else{
                Log.d("HL", "权限申请拒绝!");
            }
        }
    }

    /**
     * 打开相机,选择头像
     */
    private void takePhoto() {
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        // 确保有一个活动来处理意图
        if (takePhotoIntent.resolveActivity(getPackageManager()) != null) {
            // 创建保存图片的文件夹
            File imageFile = null;
            try {
                imageFile = createImageFile();
            }catch (Exception e){
                e.printStackTrace();
            }
            if (imageFile != null) {
                //TODO imageUri 用来接收拍摄的这张照片的真实路径
                imageUri = FileProvider.getUriForFile(this, "com.example.takePhoto.fileprovider", imageFile);
            }

            takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST_CODE);
        }
    }

    /**
     * 创建一个存放拍的照片的文件
     */
    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault())
                .format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        Log.d("HL", imageFileName);
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(
                imageFileName,  /* prefix */
                ".bmp",         /* suffix */
                storageDir      /* directory */
        );
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TAKE_PHOTO_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                try {
                    InputStream inputStream = getContentResolver().openInputStream(imageUri);
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    mImg.setImageBitmap(bitmap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_44950283/article/details/133076332