Reputation: 478
I am using permission runtime in app because android 6+ need it for dangerous permission but until force stop app my code not save file in memory even though user allow this permission in dialog.
My code for get permission runtime:
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();
}
Listener for check granted or denied from user:
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");
}
}
}
And error logcat :
java.io.FileNotFoundException: /storage/1B0A-390B/hamed-baradaran.mp3: open failed: EACCES (Permission denied)
SaveFile method in this :
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();
}
}
Please help me
Upvotes: 0
Views: 785
Reputation: 949
And try this code to saveImage
public static String SaveImage(Bitmap finalBitmap) {
String filePath;
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images_camera");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".png";
// filePath = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
filePath = file.getAbsolutePath();
//String tmpFilePath = file.getPath().toString();
IRoidAppHelper.Log("tmpFilePath", filePath);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return filePath;
}
Upvotes: 1
Reputation: 949
Hello can you try Permission Request when app start. I think there error because when u check Permission first time then get error but may be second time image saved my be try it..
Upvotes: 1