Android adapts to 8.0.6.0 to turn on the mobile phone to take pictures to get the photo path

 When you use it, just copy it and you can write the necessary remarks. Welcome to the guidance of the gods. Some codes are pieced together, and then my own summary.

First configure:

Configure it in the manifest file

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="(你的包名).fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths"></meta-data>
</provider>

Create an xml folder under the rec file and create an xml file inside

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>
The java code is as follows:
/**
      * Use the camera
      */
 private void useCamera() {    
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/test/" + System.currentTimeMillis() + ".jpg");
        file.getParentFile().mkdirs();

        // change Uri com.xykj.customview.fileprovider attention and xml is consistent
         Uri uri = FileProvider. GetUriForFile ( the this , "com.example.administrator.myapplication.fileprovider" , File );
         // add permissions
         intent.addFlags (Intent . FLAG_GRANT_READ_URI_PERMISSION );

        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, REQUEST_CAMERA);
    }
    public void applyWritePermission() {

        String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};

        if (Build.VERSION. SDK_INT >= 23 ) {
             int check = ContextCompat. checkSelfPermission ( this , permissions[ 0 ]);
             // Is the permission granted GRANTED---authorized DINIED---rejected
 if (check == PackageManager. PERMISSION_GRANTED ) {
                 //Call the camera
 useCamera();                            
            } else {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        } else {
            useCamera();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            useCamera();
        } else {
             // Did not get the permission, request a new one, or close the app
             Toast. makeText ( this , "storage permission required" , Toast. LENGTH_SHORT ).show();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
//            Log.e("TAG", "---------" + FileProvider.getUriForFile(this, "com.xykj.customview.fileprovider", file));
            //在手机相册中显示刚拍摄的图片
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri contentUri = Uri. fromFile ( file );
                String path = contentUri.getPath();
                Log. e ( "TAGSSSSSSSSS" , contentUri.toString());
                 //File path
                 String absolutePath = file .getAbsolutePath();
                 //File name
                 String parent = file .getName();
                Log.e("TAGQQQQQQQQQ", parent + "===" + absolutePath);
                mediaScanIntent.setData(contentUri);
                sendBroadcast (mediaScanIntent);
                //Set the picture
 picture .setImageBitmap(BitmapFactory. decodeFile ( file .getAbsolutePath()));                
            }else{
                File photoFile = new File( photoPath );
                 if (photoFile.exists()) {
                     //Load the picture into the bitmap through the picture address
                     Bitmap bm = BitmapFactory. decodeFile (photoFile.getAbsolutePath());
                     //Display the taken photo To the interface
                     //This is the path to return
 // results.confirm(pathsa);
                     Toast. makeText (MainActivity. this , "through" , Toast. LENGTH_LONG ).show();
                } else {
                    Toast. makeText (MainActivity. this , "The picture file does not exist" , Toast. LENGTH_LONG ).show();
                }
            }
        }
    }

    / **
      * taking pictures, photographs path
      * /
 public void jsPath () {
         // get the SD card installed state
 String = State Environment. GetExternalStorageState ();
         IF (. State.equals (Environment MEDIA_MOUNTED )) {            

            //Set the image save path
 photoPath = SAVED_IMAGE_PATH + "/" + System. currentTimeMillis () + ".png" ;            

            File imageDir = new File( photoPath );
             if (!imageDir.exists()) {
                 try {
                     //Generate a new file according to a file address to save the photo
                     imageDir.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace ();
                }
            }
            takePhotoByMethod1();
        } else {
            Toast. makeText (MainActivity. this , "SD card is not inserted" , Toast. LENGTH_SHORT ).show();
        }
    }
    void Private takePhotoByMethod1 () {
         // instantiate intent, the camera pointing
         the Intent Intent = new new the Intent (MediaStore. ACTION_IMAGE_CAPTURE );
         // instantiate the path image file
         File Photofile = new new File ( the PhotoPath );
         // After setting the camera save the image file
         intent.putExtra (MediaStore. EXTRA_OUTPUT , Uri. fromFile (Photofile));
         // start taking pictures activity and get return data
         startActivityForResult (the Intent, REQUEST_CAMERA );
    }
The above is the necessary execution code.

below:

switch (v.getId()) {
    case R.id.take_photo:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            applyWritePermission();
        }else{
            jsPath();
        }
        break;
}

点击这个按钮就可以实现, 新手第一 次写 请多多指教。

Guess you like

Origin blog.csdn.net/q992767879/article/details/79654733