来自果冻豆的牛轧糖新手尝试将文本文件写入 SD 卡我知道我现在必须请求权限,但找不到任何有效的代码
尝试了以下方法
StringBuilder bodyStr=new StringBuilder();
bodyStr.append(data1Str.toString()).append(",").append(data2Str.toString()).append(",").append(data3Str.toString()).append(",").append(data4Str.toString()).append(",").append(data5Str.toString()).append(",").append(data22Str.toString()).append(",").append(data23Str.toString()).append(lineSep);;
String bodytextStr=bodyStr.toString();
boolean hasPermission = (ContextCompat.checkSelfPermission(data_entry.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
ActivityCompat.requestPermissions(data_entry.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
}
try {
File myFile = new File(fileName);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(bodytextStr);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
回来了[权限被拒绝]
已在清单中设置常用权限
任何我出错的地方的想法
任何帮助表示赞赏
Mark
您要么拥有权限并且可以在写入文件的地方执行 try catch 块,要么必须在 onRequestPermissionsResult 中执行此操作。
就像是 :
public void yourMethod(){
boolean hasPermission = (ContextCompat.checkSelfPermission(data_entry.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if(hasPermission){
// write
}else{
// ask the permission
ActivityCompat.requestPermissions(data_entry.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
// You have to put nothing here (you can't write here since you don't
// have the permission yet and requestPermissions is called asynchronously)
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// The result of the popup opened with the requestPermissions() method
// is in that method, you need to check that your application comes here
if (requestCode == REQUEST_WRITE_STORAGE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// write
}
}
}
我建议您检查此链接:https://developer.android.com/training/permissions/requesting.html https://developer.android.com/training/permissions/requesting.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)