天天看点

Android------权限

普通权限:app在安装时候,询问你的,不允许就装不成 例如访问网络的权限

危险权限:app已经装好了,在用户使用过程中,请求你允许的权限,下图中全是危险权限包括访问存储等

Android------权限

使用权限应该在AndroidManifest.xml这个文件中,凡是在AndroidManifest.xml文件写的权限,这个app在安装时都会询问是否同意,,,

重点

所有权限包括普通权限和危险权限在安装时询问一遍,才能安装成功,在安装过后,那些危险权限在用户使用时会再次询问是否同意使用该权限,同意则第二次使用就不会再询问了,如果需要关闭改权限,则应该在手机设置里面讲权限关闭,这样当用户再次访问时,就需要再次同意

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

例如向公有文件写内容

(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
            String str ="hello world";
            File dir= Environment.getExternalStorageDirectory();
            File testfile=new File(dir,"testpublicsdfile");
            FileOutputStream fos= null;
            try {
                fos = new FileOutputStream(testfile);
                fos.write(str.getBytes());
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn  =(Button)findViewById(R.id.btnwrite);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str ="hello world";
                if(ContextCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new  String[]
                                    {Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                            Manifest.permission.READ_EXTERNAL_STORAGE},1);

                }else {
                    //往其外存公有文件写,牵扯到一个问题,权限,得要权限
                    File dir= Environment.getExternalStorageDirectory();
                    File testfile=new File(dir,"testpublicsdfile");
                    try {
                        FileOutputStream fos = new FileOutputStream(testfile);
                        fos.write(str.getBytes());
                        fos.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }