我在應用程序中使用權限運行時,因爲Android 6+需要它的危險權限,但直到強制停止應用我的代碼不保存內存中的文件,即使用戶在對話框中允許此權限。獲得錯誤許可write_external_storage與運行時權限
我對獲得許可的運行時代碼:
if(ContextCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
}else{
saveFile();
}
監聽從用戶授予或拒絕檢查:
public void onRequestPermissionsResult(int requestCode,String[] permission,int[] grantedResult){
super.onRequestPermissionsResult(requestCode, permission, grantedResult);
switch(requestCode){
case 1:
if(grantedResult.length > 0 && grantedResult[0] == PackageManager.PERMISSION_GRANTED){
Log.i("TAG","Permission Granted");
}else{
Log.i("TAG","Permission Denied");
}
}
}
和錯誤的logcat:
java.io.FileNotFoundException: /storage/1B0A-390B/hamed-baradaran.mp3: open failed: EACCES (Permission denied)
SAVEFILE方法在此:
public void saveFile(){
InputStream in;
OutputStream out;
try{
in = getResources().openRawResource(R.raw.hamedbaradaran);
out = new FileOutputStream(Environment.getExternalStorageDirectory()+"/hamed-baradaran.mp3");
byte[] buffer = new byte[1024];
int length;
while((length = in.read(buffer)) > 0)
out.write(buffer,0,length);
out.flush();
out.close();
in.close();
}catch(Exception e){
e.printStackTrace();
}
}
請幫我
你想讀的任何文件?另外,你是否也向Manifest添加了許可? – 2016-11-12 09:54:15
不,我想保存文件 –
是的,我增加了清單的權限 –