BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/...

Recently I was doing a demo that selects photos and added to the imageview. I found that I can select it, but it can’t be displayed. Obviously, the path was successfully obtained. Every time I went to BitFactory.decodeFile, it didn’t work. I checked the solutions of many bloggers, but it didn’t work. , Baidu finally found a way in Open Source China! Share with everyone!
First add permissions in AndroidManifest.xml:

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

Then add permissions dynamically in MainActivity.java (or your own Activity file), that is, ask every time you open the app

protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        askPermissions();
        }
 private void askPermissions() {
    
    //动态申请权限!
        if (Build.VERSION.SDK_INT >= 23) {
    
    
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {
    
    Manifest.permission.READ_CONTACTS,Manifest.permission.WRITE_CONTACTS,//联系人的权限
                Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE};//读写SD卡权限
            //验证是否许可权限
            for (String str : permissions) {
    
    
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
    
    
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                }
            }
        }

That's it~ Try it! Welcome to communicate!

Guess you like

Origin blog.csdn.net/qq_41446977/article/details/112546824