android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/picFolder/1.jpg exposed beyond app through ClipData.Item.getUri()

后端 未结 2 1537
我寻月下人不归
我寻月下人不归 2021-01-03 08:36

I am trying to take a photo from the phone\'s camera using this code:

activity_main.xml:




        
相关标签:
2条回答
  • 2021-01-03 09:08

    Try this! Just paste the below code in activity onCreate()

    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());
    

    It will ignore URI exposure

    0 讨论(0)
  • 2021-01-03 09:10

    If your targetSdkVersion >= 24, then we have to use FileProvider class to give access to the particular file or folder to make them accessible for other apps.

    1) First Add a FileProvider tag in AndroidManifest.xml under tag as below:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        ...
        <application
            ...
            <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.my.package.name.provider"
            android:exported="false"
            android:grantUriPermissions="true"
            tools:replace="android:authorities">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"
                tools:replace="android:resource"/>
        </provider> 
        </application>
    </manifest>
    

    2) Then create a provider_paths.xml file in res/xml folder. Folder may be needed to created if it doesn't exist.

    <paths>
        <external-path name="external_files" path="."/>
    </paths>
    

    3) Now edit your activity class file as below:

    Uri outputFileUri = Uri.fromFile(newfile);
    

    to

    Uri outputFileUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID, newfile);
    

    UPDATE #1

    Update your MainActivity.java with this:

    import android.Manifest;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.net.Uri;
    import android.os.Build;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    import android.support.v4.content.FileProvider;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.Toast;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity {
    
    //    private MyTessOCR mTessOCR = new MyTessOCR(MainActivity.this);
    
        private Button takePictureButton;
        private ImageView imageView;
    
    
    
    
    
        int TAKE_PHOTO_CODE = 0;
        public static int count = 0;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            if (checkPermissions()){
                //  permissions  granted.
    
            }
    
            final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
            File newdir = new File(dir);
            if (!newdir.exists()) {
                newdir.mkdir();
            }
    
            Button capture = (Button) findViewById(R.id.btnCapture);
            capture.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
    
                    // Here, the counter will be incremented each time, and the
                    // picture taken by camera will be stored as 1.jpg,2.jpg
                    // and likewise.
                    count++;
                    String file = dir+count+".jpg";
                    File newfile = new File(file);
                    try {
                        newfile.createNewFile();
                    }
                    catch (IOException e)
                    {
                    }
    
                    //     Uri outputFileUri = Uri.fromFile(newfile);
                    Uri outputFileUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID, newfile);
    
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
    
                    startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
                }
            });
    
    
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data)
        {
            super.onActivityResult(requestCode, resultCode, data);
    
            if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
                Log.d("CameraDemo", "Pic saved");
            }
        }
    
    
    
    
    
        public static final int MULTIPLE_PERMISSIONS = 10; // code you want.
    
        String[] permissions= new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION};
    
    
    
    
        private  boolean checkPermissions() {
            int result;
            List<String> listPermissionsNeeded = new ArrayList<>();
            for (String p:permissions) {
                result = ContextCompat.checkSelfPermission(MainActivity.this,p);
                if (result != PackageManager.PERMISSION_GRANTED) {
                    listPermissionsNeeded.add(p);
                }
            }
            if (!listPermissionsNeeded.isEmpty()) {
                ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),MULTIPLE_PERMISSIONS );
                return false;
            }
            return true;
        }
    
    
        @Override
        public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
            switch (requestCode) {
                case MULTIPLE_PERMISSIONS:{
                    if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                        // permissions granted.
                    } else {
    //                    Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG)
    //                            .show();
                        }
                        // permissions list of don't granted permission
                    }
                    return;
                }
            }
    
    
    
        private void doOCR()
        {
            //   String temp = mTessOCR.getOCRResult(bitmap);
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题