android studio calls camera to take photos and demonstrates the specific steps

Demonstrate the function of the code, call the camera to take photos, and display the photos if successful.

The first step is to define a button for calling the camera to take photos, and ImageView is used to store and display the photos taken.

<Button
        android:id="@+id/take_photo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="take photo"
        />
    <ImageView
        android:id="@+id/picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        />

The second step starts to write the specific logic of calling the camera

package example.com.test;
//Logic, first create the file, then encapsulate it into uri object, then wrap it in intent and call the camera. After that, there will be one.
//Return the result and display it if it is successful
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    public static final int TAKE_PHOTO=1;//Declare a request code to identify the returned result
    private ImageView picture;
    private Uri imageUri;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button takephoto=findViewById(R.id.take_photo);
        picture=findViewById(R.id.picture);
        takephoto.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                File outputImage=new File(getExternalCacheDir(),"output_image.jpg");
                /*
                Create a File object to store the pictures taken by the camera. We name this picture output_image.jpg
                And store it in the Application Association cache directory. Call getExternalCacheDir() to get the directory. Why
                What about caching directories with associations? Since Android 6.0 started, when reading and writing sd card columns, you must have permission to use them,
                You can skip this step by applying the associated directory
                 */
                try//Determine whether the picture exists. If it exists, delete it and create it directly
                {
                    if(outputImage.exists())
                    {
                        outputImage.delete();
                    }
                    outputImage.createNewFile();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                if(Build.VERSION.SDK_INT>=24)
                    //Determine whether the Android version is higher than 7.0. If it is higher, call the higher method, and if it is lower, call the lower method
                    //Convert file to Uri object
                    /*
                    The reason for this is that it is not safe to use the local real path directly after Android 7.0, and an exception will be thrown.
                    FileProvider Is a special content provider that protects data
                     */
                {
                    imageUri= FileProvider.getUriForFile(MainActivity.this,
                            "com.example.cameraalbumtest.fileprovider",outputImage);
                    /*
                    First parameter: context object
                    Second parameter: any unique string
                    Third parameter: file object
                     */

                }
                else {
                    imageUri=Uri.fromFile(outputImage);
                }
                //Using the implicit Intent, the system will find the corresponding activity, that is, calling the camera and storing it
                Intent intent=new intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                startActivityForResult(intent,TAKE_PHOTO);
                //Call will return the opening method of the result. If the result is returned successfully, it will be displayed
            }
        });
    }
    //The function to process the returned result. The following is the processing method of implicit intent's returned result. For details, see my previous explanation of intent
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode)
        {
            case TAKE_PHOTO:
                if(resultCode==RESULT_OK)
                {
                    try
                    {
                         Bitmap bitmap= BitmapFactory.decodeStream(getContent-
                                Resolver().openInputStream(imageUri));
                         picture.setImageBitmap(bitmap);
                         //Parse the image into a Bitmap object and show it
                    }
                    catch (FileNotFoundException e)
                    {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }
    }
}

Step 3 just mentioned the content provider, so now we register the content provider in manifest.xml, where the value of android:name is fixed,

Android: the values of authors must be consistent with the second parameter of FileProvider.getUriForFile. In this case, we also use < meta data to formulate the uri path and reference a resource. Of course, this resource has not been created yet. We will create it in step 4.

<provider
            android:authorities="com.example.cameraalbumtest.fileprovider"
            android:name="android.support.v4.content.FileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>

Step 4: create an xml directory in the res directory. The directory is directory. Then create an xml source file in this directory. The modification code is as follows:

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

</paths>

Where < external path is used to specify the uri to share, and the name can be filled in freely. If path is empty, the whole sd card can be shared

Step 5: in order to be compatible with the old Android system, we still intend to add a permission to declare the permission to access the sd card.

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

 

Tags: Android FileProvider xml Java

Posted on Tue, 31 Dec 2019 19:40:28 -0500 by PC Nerd