解决安卓7.0系统写入SD卡权限失败问题

 余温
2018年05月09日 18时07分
 android

如图所示,在mainfest文件中声明了SD卡的读和写权限,仍旧报错:

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

安卓23.0版本以上,不仅仅要设置上面的权限,还要在对SD卡有读写操作的地方授权,下面是公共类:

import android.Manifest;import android.app.Activity;import android.content.pm.PackageManager;import android.support.v4.app.ActivityCompat;public class PermisionUtils {

    // Storage Permissions
    private static final int REQUEST_EXTERNAL_STORAGE = 1;    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};    /**
     * Checks if the app has permission to write to device storage
     * If the app does not has permission then the user will be prompted to
     * grant permissions
     *
     * @param activity
     */
    public static void verifyStoragePermissions(Activity activity) {        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);        if (permission != PackageManager.PERMISSION_GRANTED) {            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }
}

然后直接在需要授权的地方调用:

verifyStoragePermissions(this);

在SD卡写入xml文件

//生成XML文件
public void click(View v) throws IOException {
    //获取实例
    try {
        verifyStoragePermissions(this);//请求写入权限
        XmlSerializer serializer = Xml.newSerializer();
        //设置序列化
        File file = new File(Environment.getExternalStorageDirectory().getPath(), "texe.xml");
        FileOutputStream fos = new FileOutputStream(file);
        serializer.setOutput(fos, "utf-8");
        //写文件头
        serializer.startDocument("utf-8", true);
        //写根节点
        serializer.startTag(null, "smss");
        serializer.startTag(null, "sms");
        serializer.text("知乎");
        serializer.endTag(null, "sms");
        serializer.endTag(null, "smss");
        fos.close();
        System.out.println("保存成功");
    } catch (Exception e) {
        System.out.println("保存失败");
        System.out.println("--------------------------------------------");
        e.printStackTrace();
        System.out.println("-----------------------------------");
    }

}


{{vo.nickname}}:{{vo.content}}

{{vo.time}} 回复


  • {{level.nickname}} 回复 {{level.father_nickname}}{{level.content}}
  • {{level.time}} 回复


@
登陆后评论