Camera is called and displayed in Android.

Keywords: Android xml FileProvider encoding

Here is mainly through the click of the button to open the camera, and then the pictures taken are displayed.

First, add these two permissions to Android manifest.xml:

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

The layout file code of MainActivity is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <Button
        android:id="@+id/btn_take_photo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Photograph"
        android:textSize="20sp" />

    <ImageView
        android:id="@+id/picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp" />

</LinearLayout>

The layout is very simple, just a Button and an ImageView

The java code of MainActivity is as follows:

public class MainActivity extends AppCompatActivity {
    public static final int TAKE_PHOTO = 1;
    private ImageView picture;
    private Uri imageUri;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button takePhoto = findViewById(R.id.btn_take_photo);
        picture = findViewById(R.id.picture);
        mContext = MainActivity.this;


        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Create a File object to save the pictures taken by the camera. Here, name the picture output_image.jpg
                // And store it in the Application Association cache directory of SD card
                File outputImage = new File(getExternalCacheDir(), "output_image.jpg");

                // Change settings for photos
                try {
                    // Delete if last photo exists
                    if (outputImage.exists()) {
                        outputImage.delete();
                    }
                    // Create a new file
                    outputImage.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // If Android version is greater than or equal to 7.0
                if (Build.VERSION.SDK_INT >= 24) {
                    // Convert the File object to an encapsulated Uri object
                    imageUri = FileProvider.getUriForFile(MainActivity.this, "com.example.lenovo.cameraalbumtest.fileprovider", outputImage);
                } else {
                    // Convert the File object to a Uri object that identifies the local real path of the image output_image.jpg
                    imageUri = Uri.fromFile(outputImage);
                }

                // Dynamic application authority
                if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.CAMERA}, 100);
                } else {
                    // Start camera program
                    startCamera();
                }

            }
        });

    }

    private void startCamera() {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // The output address of the specified picture is imageUri
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_PHOTO);
    }


    // Use startActivityForResult() method to start the callback of Intent
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case TAKE_PHOTO:
                if (requestCode == TAKE_PHOTO) {
                    try {
                        // Resolve picture to Bitmap object
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        // Show pictures
                        picture.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 100:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Start camera program
                    startCamera();
                } else {
                    Toast.makeText(mContext, "No authority", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }
}

Is that all? Of course not. Because the content provider is used, we need to register in Android manifest.xml, and add the following code to the application tag in Android manifest.xml:

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

In the provider tag, name is a fixed value, and the values of the authors property must be consistent with the second parameter in the FileProvider.getUriForFile() method just now. In addition, in the content of the provider tag, the meta data tag is used to specify the shared path of the Uri, and a @ xml/file_paths resource is referenced. This resource does not exist yet. Now let's create this resource.

Right click res Directory - > New - > directory, create an xml directory, then right click xml Directory - > New - > file, create a file [paths. xml file, and modify it to the following:

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

Posted by mmilano on Thu, 31 Oct 2019 03:09:06 -0700