android6.0创建文件问题

Android在6.0有了动态权限管理,在文件创建时就需要动态权限。

Android的API对应版本如下:

[img]http://dl2.iteye.com/upload/attachment/0124/6375/b77f2ff0-dd51-3da2-847a-a1719ac20cbe.png[/img]

[img]http://dl2.iteye.com/upload/attachment/0124/6379/9eea8a24-0be1-36ac-b0e0-da29c6cf759b.png[/img]

首先检查并申请权限:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
int writePermission = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(writePermission != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_CODE);
return ;
}
}

申请权限回调:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == REQUEST_CODE){
if(permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && grantResults[0] == PackageManager.PERMISSION_GRANTED){
saveFile();
}else{
Toast.makeText(this,"授权失败",Toast.LENGTH_SHORT).show();
}
}
}

保存文件saveFile代码如下:
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory(), "lmlfiletest.txt");
if(file.exists()){
file.delete();
}
try {
FileOutputStream fos = new FileOutputStream(file);
String info = etInfo.getText().toString();
fos.write(info.getBytes("utf-8"));
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(this, "创建成功!", Toast.LENGTH_SHORT).show();
}

测试成功!

你可能感兴趣的:(android)