Android在6.0有了动态权限管理,在文件创建时就需要动态权限。
Android的API对应版本如下:
首先检查并申请权限:
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();
}
测试成功!