九天 Android 11获取文件读写权限

protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );
        
        requestPermission( this );

    }


private void requestPermission(Context context) { 
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 
            // 先判断有没有权限
            if (Environment.isExternalStorageManager()) { 

            } else { 
                Intent intent = new Intent( Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION );
                intent.setData( Uri.parse( "package:" + context.getPackageName() ) );
                startActivityForResult( intent,0 );
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
            // 先判断有没有权限
            if (ActivityCompat.checkSelfPermission( this, Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission( this, Manifest.permission.WRITE_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED) { 
            } else { 
                ActivityCompat.requestPermissions( this, new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0 );
            }
        } else { 

        }
    }

    public void onRequestPermissionsResult(int requestCode,

                                           String[] permissions,

                                           int[] grantResults) { 
        super.onRequestPermissionsResult( requestCode, permissions, grantResults );
        if (requestCode == 0) { 
            if (ActivityCompat.checkSelfPermission( this, Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission( this, Manifest.permission.WRITE_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED) { 

            } else { 

            }
        }
    }

    protected void onActivityResult(int requestCode, int resultCode,

                                    Intent data) { 
        super.onActivityResult( requestCode, resultCode, data );
        if (requestCode == 0 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 
            if (Environment.isExternalStorageManager()) { 

            } else { 

            }
        }
    }
android 
	defaultConfig { 
		targetSdkVersion 30
	}
}
    原文作者:guigujiagoushijishur
    原文地址: https://blog.csdn.net/kenanke/article/details/123369537
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞