Let's first write a method that checks for the SDCard and if it is possible to write to it:
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
The method returns true if it is possible to write to SDCard or false if it does not exist or for some reason can not write to it. / p>
We need two methods to save byte [], one to save to internal memory and another to save to SDCard .
Save to internal memory:
public void saveArrayToInternalStorage(String fileName, byte[] imagem){
try{
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(imagem);
fos.close();
}catch (IOException e) {
Log.w("InternalStorage", "Error writing", e);
}
}
Save to SDCard:
MediaStore does not see the images we will use getExternalFilesDir()
to get the Path to SDCard.
public void saveArrayToSDCard(String fileName, bytes[] imagem){
File path = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File file = new File(path, fileName);
try{
OutputStream os = new FileOutputStream(file);
os.write(imagem);
os.close()
} catch (IOException e) {
Log.w("ExternalStorage", "Error writing", e);
}
}
How to use:
if(isExternalStorageWritable(){
saveArrayToSDCard("nomeDaImagem", imagemEmBytes);
}else{
saveArrayToInternalStorage("nomeDaImagem", imagemEmBytes);
}
If the application is to run in versions prior to Android 4.4, you must obtain the WRITE_EXTERNAL_STORAGE permission, add the following to Manifest
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
...
</manifest>
Note: Images recorded by these methods will be deleted when the application is uninstalled.
Source: Android Storage Options