cameraKit-android output video - android

Does anyone use the CameraKit-Android by gogopop? My problem is that I set the listener of video but the outputfile is null. Anyone know how to solve it?
this is my code:
cameraView.getCamera().setVideoQuality(CameraKit.Constants.VIDEO_QUALITY_720P);
cameraView.getCamera().startRecordingVideo();
cameraView.getCamera().setCameraListener(new CameraListener() {
#Override
public void onVideoTaken(final File video) {
super.onVideoTaken(video);
/* new Thread(new Runnable() {
#Override
public void run() {
final byte[] videoBytes = FileUtils.File2byte(video.getAbsolutePath());
if (!isExit) {
new Thread(new Runnable() {
#Override
public void run() {
saveFile(videoBytes);
}
}).start();
}
isExit = false;
}
}).start();*/
}
});
I've used to make a new file to save the mp4, but when I'm recording a video longer than one minute, the app is OOM. Anyone can help me? Thanks.

i slove it. this is not cameraKit-android issuse. it is the Android 's problem,it have two point:
the file is exit, but you don't notification the system. so you should :
cameraView.getCamera().setCameraListener(new CameraListener() {
#Override
public void onVideoTaken(final File video) {
super.onVideoTaken(video);
//notify system refresh
Uri localUri = Uri.fromFile(video);
Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
sendBroadcast(localIntent);
try this guys idea, i use it save susscess:
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/milai/";
File appDir = new File(path);
if (!appDir.exists()) {
appDir.mkdir();
}
mVideoFile = new File(mPreview.getView().getContext().getExternalFilesDir(null), getPicTime()+".mp4");
String myFile = path+getPicTime()+".mp4";
mMediaRecorder.setOutputFile(myFile);
it look the same , but i don't know why success. if eveybody have other problem, can ask me . i will try to help you.

My solution for this problem;
public static void saveVideoToFile( File video) {
try {
File newfile;
FileInputStream fileInputStream = new FileInputStream(video);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath() + "/" + "Your File Name" + "/");
if (!dir.exists()) {
dir.mkdirs();
}
newfile = new File(dir, "save_" + System.currentTimeMillis() + ".mp4");
if (newfile.exists()) newfile.delete();
OutputStream out = new FileOutputStream(newfile);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = fileInputStream.read(buf)) > 0) {
out.write(buf, 0, len);
}
fileInputStream.close();
out.close();
MyLog.log("Copy file successful.");
} catch (Exception e) {
e.printStackTrace();
}
}

Related

FFmpeg audio video merge command

Can you let me know , whether the below command is the correct
one for video audio merge ?
vabsolutePath= video file absolute path (only video),
aabsolutePath= audio file absolute path (only audio)
String ccommand[] = {"-i",vabsolutePath,"-i",aabsolutePath, "-c:v", "copy", "-c:a", "aac","-shortest", dabsolutePath};
The below code is used in android for merging.
Here the issue is the code is executing, but the output merge file "result.mp4" is not playable/not produced.
Could you please help to find out the issue in code/ command?
public class Mrge extends AppCompatActivity {
private Button var_button_save,var_button_send;
Uri vuri=null;
public String vabsolutePath=null, aabsolutePath=null, dabsolutePath=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.message_layout);
OutputStream out;
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
InputStream ins = getResources().openRawResource(
getResources().getIdentifier("anvkl",
"raw", getPackageName()));
byte[] buf = new byte[1024];
int n;
while (-1 != (n = ins.read(buf)))
stream.write(buf, 0, n);
byte[] bytes = stream.toByteArray();
String root = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
File createDir = new File(root + "master" + File.separator);
createDir.mkdir();
File file = new File(root + "master" + File.separator + "master.mp4");
file.createNewFile();
out = new FileOutputStream(file);
out.write(bytes);
out.close();
vabsolutePath = file.getAbsolutePath();
//-------------------------------------------------------------------
ins = getResources().openRawResource(
getResources().getIdentifier("audio",
"raw", getPackageName()));
while (-1 != (n = ins.read(buf)))
stream.write(buf, 0, n);
bytes = stream.toByteArray();
root = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
createDir = new File(root + "audio" + File.separator);
createDir.mkdir();
file = new File(root + "audio" + File.separator + "audio.aac");
file.createNewFile();
out = new FileOutputStream(file);
out.write(bytes);
out.close();
aabsolutePath = file.getAbsolutePath();
root = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
createDir = new File(root + "result" + File.separator);
createDir.mkdir();
file = new File(root + "result" + File.separator + "result.mp4");
file.createNewFile();
dabsolutePath = file.getAbsolutePath();
//------------------------------------------------------------------------
} catch (IOException e) {
e.printStackTrace();
}
String ccommand[] = {"-y", "-i",vabsolutePath,"-i",aabsolutePath, "-c:v", "copy", "-c:a", "aac","-shortest", dabsolutePath};
loadFFMpegBinary();
execFFmpegBinary(ccommand);
}
FFmpeg ffmpeg;
private void loadFFMpegBinary() {
try {
if (ffmpeg == null) {
ffmpeg = FFmpeg.getInstance(this);
}
ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
#Override
public void onFailure() {
//showUnsupportedExceptionDialog();
}
#Override
public void onSuccess() {
}
});
} catch (FFmpegNotSupportedException e) {
//showUnsupportedExceptionDialog();
} catch (Exception e) {
}
}
private void execFFmpegBinary(final String[] command) {
try {
ffmpeg.execute(command, new ExecuteBinaryResponseHandler()
{
#Override
public void onFailure(String s) {
}
#Override
public void onSuccess(String s) {
}
#Override
public void onProgress(String s) {
}
#Override
public void onStart() {
}
#Override
public void onFinish() {
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
String m="hi";
}
}
}
While it is not possible to give you a concrete answer due to lacking details I will say yes, assuming:
Your ffmpeg command is implemented properly in your code and provides no errors.
You are outputting to an appropriate output format container for your video and audio formats.
The vabsolutePath contains only video and aabsolutePath contains only audio. Otherwise use the -map option to manually select streams instead of relying on the default stream selection behavior. Otherwise it may select the wrong streams.
Try creating destination(output) file in the below way-
File moviesDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES
);
boolean success = true;
if (!moviesDir.exists()) {
success = moviesDir.mkdir();
}
if(success) {
File dest = new File(moviesDir, filePrefix + fileExtn);
int fileNo = 0;
while (dest.exists()) {
fileNo++;
dest = new File(moviesDir, filePrefix + fileNo + fileExtn);
}
....//execute ffmpeg command with dest.getAbsolutePath() as an output file path
}else
{
Snackbar.make(mainlayout, "Unable to create directory", 4000).show();
}
Use dest.getAbsolutePath() as an output file path to ffmpeg command.You can change desired directory as per your requirement.

Android : Default audio recording

I am trying to record audio with the following code.
public void onClick(DialogInterface dialog, int id) {
System.out.println("Inside Audio recording");
File storageDir = new File(Environment.getExternalStorageDirectory()+ "/filetoupload/");
if (!storageDir.exists()) {
storageDir.mkdirs();
}
try {
System.out.println("Inside Audio recording try block");
imageToStore = new File(storageDir,"" + "audio.3gp");
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(imageToStore));
System.out.println("Inside Audio recording path"+ imageToStore);
startActivityForResult(intent,CAPTURE_AUDIO);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
It will open default android recording player and let me record audio file.
So basically it will start default audio recording and should create folder name filetoupload inside SD-card and should store it is as a name audio.3gp but it is not doing same. It is storing recording inside default recording folder in device or with some other name like recording-10555454545.3gp
So how can i store this audio inside SD-card particular folder and with audio.3gp name please help.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == RQS_RECORDING) {
try {
AssetFileDescriptor videoAsset = getContentResolver()
.openAssetFileDescriptor(data.getData(), "r");
FileInputStream fis;
fis = videoAsset.createInputStream();
File root = new File(Environment
.getExternalStorageDirectory().getAbsolutePath() + "/Foldername/", "AUDIO"); // you
if (!root.exists()) {
root.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File file;
file = new File(root.getPath() + "/" + "AUD_" + timeStamp
+ ".mp3");
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
Uri fileuri = Uri.fromFile(file);
System.out.println("you Audio path"+fileuri.getpath)
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Load a file from external storage to Inputstream

i have a video file in my external directory. how can i load it to inputstream variable.
For the time being i am reading file in the res/raw folder but i want to read it from the sdcard. also i dont know about the name of the file but its path will be recieved through intent.
check the following code
public class SonicTest extends Activity
{
VideoView videoView;
String uri;
InputStream soundFile;
File file;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void play(View view)
{
new Thread(new Runnable()
{
public void run()
{
float speed= (float) 1.0;
float pitch= (float) 1.5;
float rate= (float) 1.0;
uri= Environment.getExternalStorageDirectory().toString();
uri=uri+"/video.3gp";
AndroidAudioDevice device = new AndroidAudioDevice(22050, 1);
Sonic sonic = new Sonic(22050, 1);
byte samples[] = new byte[4096];
byte modifiedSamples[] = new byte[2048];
InputStream soundFile = null;
//soundFile = getContentResolver().openInputStream(Uri.parse(uri));
soundFile=getResources().openRawResource(R.raw.video3);
Log.i("testing","check if SoundFile is correct "+soundFile);
int bytesRead;
if(soundFile != null) {
sonic.setSpeed(speed);
sonic.setPitch(pitch);
sonic.setRate(rate);
do {
try {
bytesRead = soundFile.read(samples, 0, samples.length);
} catch (IOException e) {
e.printStackTrace();
return;
}
if(bytesRead > 0) {
sonic.putBytes(samples, bytesRead);
} else {
sonic.flush();
}
int available = sonic.availableBytes();
if(available > 0) {
if(modifiedSamples.length < available) {
modifiedSamples = new byte[available*2];
}
sonic.receiveBytes(modifiedSamples, available);
device.writeSamples(modifiedSamples, available);
}
} while(bytesRead > 0);
device.flush();
}
}
} ).start();
}}
Try
File file = new File(Uri.toString());
FileInputStream fileInputStream = new FileInputStream(file);
Then you can read from the stream.
String fileName = "OfflineMap/maps.xml";
String path = Environment.getExternalStorageDirectory()+"/"+fileName;
File file = new File(path);
FileInputStream fileInputStream = new FileInputStream(file);
Here is a working code, you can InputStream with a storage file:
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"Demo.xml");
InputStream fileInputStream = new FileInputStream(file);
soundFile = openFileInput(uri);

Building new directory and pushing files in Android

I have code that I know worked in another project of mine to create a new folder if it didn't already exist and place files from my project into it. But in my new project the code does nothing. What am i doing wrong?
File directory = new File(Environment.getExternalStorageDirectory()
+ File.separator + "testing");
directory.mkdirs();
File directory2 = new File(Environment.getExternalStorageDirectory()
+ File.separator + "CandooData" + File.separator + "Meds");
if (!(directory2.isDirectory())) {
directory2.mkdirs();
}
File directory3 = new File(Environment.getExternalStorageDirectory()
+ File.separator + "CandooData" + File.separator + "Meds");
String[] files;
if (directory3.isDirectory()) {
files = directory3.list();
if (files.length == 0) {
// directory is empty
CopyAssets("medsxml", "/Meds");
}
}
See the log via logcat.
It's possible that you've missed the WRITE_EXTERNAL_STORAGE permission.
mkdirs() will work just fine, not worse than mkdir().
Below is briefly example
File folder = new File(Environment.getExternalStorageDirectory()+"/Trip");
if(!folder.exists()){
folder.mkdir();
}
File newxmlfile = new File(Environment.getExternalStorageDirectory()+"/Trip/"+ RecordID +".xml");
try{
newxmlfile.createNewFile();
}catch(IOException e){
}
use this directory.mkdir(); instead of this directory.mkdirs();
I am using this below method to make directory and save the file in to it.
private static File APP_FILE_PATH = new File("/sdcard/SpeechTutor");
p_file_Side_Slow = new File("/sdcard/SpeechTutor/P_SideMovieSlow.mp4");
p_file_Side_Medium = new File("/sdcard/SpeechTutor/P_SideMovieMedium.mp4");
p_file_Side_Fast = new File("/sdcard/SpeechTutor/P_SideMovieFast.mp4");
p_file_Front_Slow = new File("/sdcard/SpeechTutor/P_FrontMovieSlow.mp4");
p_file_Front_Medium = new File("/sdcard/SpeechTutor/P_FrontMovieMedium.mp4");
p_file_Front_Fast = new File("/sdcard/SpeechTutor/P_FrontMovieFast.mp4");
if((!(p_file_Side_Slow.exists())) || (!(p_file_Side_Medium.exists())) || (!(p_file_Side_Fast.exists()))
|| (!(p_file_Front_Slow.exists()))|| (!(p_file_Front_Medium.exists()))||(!(p_file_Front_Fast.exists()))){
ArrayList<String> files = new ArrayList<String>();
files.add("P_SideMovieSlow.mp4");
files.add("P_SideMovieMedium.mp4");
files.add("P_SideMovieFast.mp4");
files.add("P_FrontMovieSlow.mp4");
files.add("P_FrontMovieMedium.mp4");
files.add("P_FrontMovieFast.mp4");
new myAsyncTask().execute(files);
}
// AsyncTass for the Progress Dialog and to do Background Process
private class myAsyncTask extends AsyncTask<ArrayList<String>, Void, Void> {
ArrayList<String> files;
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(MainScreenActivity.this, "Speech Tutor", "Loading...");
}
#Override
protected Void doInBackground(ArrayList<String>... params) {
files = params[0];
for (int i = 0; i < files.size(); i++) {
copyFileFromAssetsToSDCard(files.get(i));
} return null;
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
// myVideoThumbnail.setImageBitmap((Bitmap)ThumbnailUtils.createVideoThumbnail(p_file_Side_Slow.getAbsolutePath(),MediaStore.Video.Thumbnails.MINI_KIND));
// myVideoView.setVideoURI(p_uri_Side_Medium);
setVideoURI(sideShow, frontshow, slowShow, mediumShow, fastShow);
}
}
// Function to copy file from Assets to the SDCard
public void copyFileFromAssetsToSDCard(String fileFromAssets){
AssetManager is = this.getAssets();
InputStream fis;
try {
fis = is.open(fileFromAssets);
FileOutputStream fos;
if (!APP_FILE_PATH.exists()) {
APP_FILE_PATH.mkdirs();
}
fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory()+"/SpeechTutor",fileFromAssets));
byte[] b = new byte[8];
int i;
while ((i = fis.read(b)) != -1) {
fos.write(b, 0, i);
}
fos.flush();
fos.close();
fis.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
All Above code will save the file as background process.

Android saving file to external storage

I have a little issue with creating a directory and saving a file to it on my android application. I'm using this piece of code to do this :
String filename = "MyApp/MediaTag/MediaTag-"+objectId+".png";
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream fos;
fos = new FileOutputStream(file);
fos.write(mediaTagBuffer);
fos.flush();
fos.close();
But it's throwing an exception :
java.io.FileNotFoundException: /mnt/sdcard/MyApp/MediaCard/MediaCard-0.png (No such file or directory)
on that line : fos = new FileOutputStream(file);
If I set the filename to : "MyApp/MediaTag-"+objectId+" it's working, but If I try to create and save the file to an another directory it's throwing the exception. So any ideas what I'm doing wrong?
And another question: Is there any way to make my files private in external storage so user can't see them in gallery, only if he connect his device as Disk Drive?
Use this function to save your bitmap in SD card
private void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
if (!myDir.exists()) {
myDir.mkdirs();
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
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();
}
}
and add this in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
EDIT: By using this line you will be able to see saved images in the gallery view.
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
look at this link also http://rajareddypolam.wordpress.com/?p=3&preview=true
The code presented by RajaReddy no longer works for KitKat
This one does (2 changes):
private void saveImageToExternalStorage(Bitmap finalBitmap) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
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();
}
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
Update 2018, SDK >= 23.
Now you should also check if the user has granted permission to external storage by using:
public boolean isStoragePermissionGranted() {
String TAG = "Storage Permission";
if (Build.VERSION.SDK_INT >= 23) {
if (this.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission is granted");
return true;
} else {
Log.v(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
public void saveImageBitmap(Bitmap image_bitmap, String image_name) {
String root = Environment.getExternalStorageDirectory().toString();
if (isStoragePermissionGranted()) { // check or ask permission
File myDir = new File(root, "/saved_images");
if (!myDir.exists()) {
myDir.mkdirs();
}
String fname = "Image-" + image_name + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
try {
file.createNewFile(); // if file already exists will do nothing
FileOutputStream out = new FileOutputStream(file);
image_bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(this, new String[]{file.toString()}, new String[]{file.getName()}, null);
}
}
and of course, add in the AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You need a permission for this
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
and method:
public boolean saveImageOnExternalData(String filePath, byte[] fileData) {
boolean isFileSaved = false;
try {
File f = new File(filePath);
if (f.exists())
f.delete();
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(fileData);
fos.flush();
fos.close();
isFileSaved = true;
// File Saved
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOException");
e.printStackTrace();
}
return isFileSaved;
// File Not Saved
}
Make sure your app has the proper permissions to be allowed to write to external storage: http://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE
It should look something like this in your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Try This :
Check External storage device
Write File
Read File
public class WriteSDCard extends Activity {
private static final String TAG = "MEDIA";
private TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.TextView01);
checkExternalMedia();
writeToSDFile();
readRaw();
}
/**
* Method to check whether external media available and writable. This is
* adapted from
* http://developer.android.com/guide/topics/data/data-storage.html
* #filesExternal
*/
private void checkExternalMedia() {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Can't read or write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
tv.append("\n\nExternal Media: readable=" + mExternalStorageAvailable
+ " writable=" + mExternalStorageWriteable);
}
/**
* Method to write ascii text characters to file on SD card. Note that you
* must add a WRITE_EXTERNAL_STORAGE permission to the manifest file or this
* method will throw a FileNotFound Exception because you won't have write
* permission.
*/
private void writeToSDFile() {
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data-
// storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
tv.append("\nExternal file system root: " + root);
// See
// http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File(root.getAbsolutePath() + "/download");
dir.mkdirs();
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Hi , How are you");
pw.println("Hello");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you"
+ " add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nFile written to " + file);
}
/**
* Method to read in a text file placed in the res/raw directory of the
* application. The method reads in all lines of the file sequentially.
*/
private void readRaw() {
tv.append("\nData read from res/raw/textfile.txt:");
InputStream is = this.getResources().openRawResource(R.raw.textfile);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr, 8192); // 2nd arg is buffer
// size
// More efficient (less readable) implementation of above is the
// composite expression
/*
* BufferedReader br = new BufferedReader(new InputStreamReader(
* this.getResources().openRawResource(R.raw.textfile)), 8192);
*/
try {
String test;
while (true) {
test = br.readLine();
// readLine() returns null if no more lines in the file
if (test == null) break;
tv.append("\n" + " " + test);
}
isr.close();
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nThat is all");
}
}
I have created an AsyncTask for saving bitmaps.
public class BitmapSaver extends AsyncTask<Void, Void, Void>
{
public static final String TAG ="BitmapSaver";
private Bitmap bmp;
private Context ctx;
private File pictureFile;
public BitmapSaver(Context paramContext , Bitmap paramBitmap)
{
ctx = paramContext;
bmp = paramBitmap;
}
/** Create a File for saving an image or video */
private File getOutputMediaFile()
{
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ ctx.getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
protected Void doInBackground(Void... paramVarArgs)
{
this.pictureFile = getOutputMediaFile();
if (this.pictureFile == null) { return null; }
try
{
FileOutputStream localFileOutputStream = new FileOutputStream(this.pictureFile);
this.bmp.compress(Bitmap.CompressFormat.PNG, 90, localFileOutputStream);
localFileOutputStream.close();
}
catch (FileNotFoundException localFileNotFoundException)
{
return null;
}
catch (IOException localIOException)
{
}
return null;
}
protected void onPostExecute(Void paramVoid)
{
super.onPostExecute(paramVoid);
try
{
//it will help you broadcast and view the saved bitmap in Gallery
this.ctx.sendBroadcast(new Intent("android.intent.action.MEDIA_MOUNTED", Uri
.parse("file://" + Environment.getExternalStorageDirectory())));
Toast.makeText(this.ctx, "File saved", 0).show();
return;
}
catch (Exception localException1)
{
try
{
Context localContext = this.ctx;
String[] arrayOfString = new String[1];
arrayOfString[0] = this.pictureFile.toString();
MediaScannerConnection.scanFile(localContext, arrayOfString, null,
new MediaScannerConnection.OnScanCompletedListener()
{
public void onScanCompleted(String paramAnonymousString ,
Uri paramAnonymousUri)
{
}
});
return;
}
catch (Exception localException2)
{
}
}
}
}
Probably exception is thrown because there is no MediaCard subdir. You should check if all dirs in the path exist.
About visibility of your files: if you put file named .nomedia in your dir you are telling Android that you don't want it to scan it for media files and they will not appear in the gallery.
For API level 23 (Marshmallow) and later, additional to uses-permission in manifest, pop up permission should also be implemented, and user needs to grant it while using the app in run-time.
Below, there is an example to save hello world! as content of myFile.txt file in Test directory inside picture directory.
In the manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Where you want to create the file:
int permission = ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (permission != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,PERMISSIONS_STORAGE, 1);
}
File myDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Test");
myDir.mkdirs();
try
{
String FILENAME = "myFile.txt";
File file = new File (myDir, FILENAME);
String string = "hello world!";
FileOutputStream fos = new FileOutputStream(file);
fos.write(string.getBytes());
fos.close();
}
catch (IOException e) {
e.printStackTrace();
}
Old way of saving files might not work with new versions of android, starting with android10.
fun saveMediaToStorage(bitmap: Bitmap) {
//Generating a dummy file name
val filename = "${System.currentTimeMillis()}.jpg"
//Output stream
var fos: OutputStream? = null
//For devices running android >= Q
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//getting the contentResolver
context?.contentResolver?.also { resolver ->
//Content resolver will process the contentvalues
val contentValues = ContentValues().apply {
//putting file information in content values
put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
}
//Inserting the contentValues to contentResolver and getting the Uri
val imageUri: Uri? =
resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
//Opening an outputstream with the Uri that we got
fos = imageUri?.let { resolver.openOutputStream(it) }
}
} else {
//These for devices running on android < Q
//So I don't think an explanation is needed here
val imagesDir =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
val image = File(imagesDir, filename)
fos = FileOutputStream(image)
}
fos?.use {
//Finally writing the bitmap to the output stream that we opened
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it)
context?.toast("Saved to Photos")
}
}
Reference- https://www.simplifiedcoding.net/android-save-bitmap-to-gallery/
since android 4.4 file saving has been changed. there is
ContextCompat.getExternalFilesDirs(context, name);
it retuns an array.
when name is null
the first value is like /storage/emulated/0/Android/com.my.package/files
the second value is like
/storage/extSdCard/Android/com.my.package/files
android 4.3 and less it retuns a single item array
parts of little messy code but it demonstrates how it works:
/** Create a File for saving an image or video
* #throws Exception */
private File getOutputMediaFile(int type) throws Exception{
// Check that the SDCard is mounted
File mediaStorageDir;
if(internalstorage.isChecked())
{
mediaStorageDir = new File(getFilesDir().getAbsolutePath() );
}
else
{
File[] dirs=ContextCompat.getExternalFilesDirs(this, null);
mediaStorageDir = new File(dirs[dirs.length>1?1:0].getAbsolutePath() );
}
// Create the storage directory(MyCameraVideo) if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
output.setText("Failed to create directory.");
Toast.makeText(this, "Failed to create directory.", Toast.LENGTH_LONG).show();
Log.d("myapp", "Failed to create directory");
return null;
}
}
// Create a media file name
// For unique file name appending current timeStamp with file name
java.util.Date date= new java.util.Date();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.ENGLISH) .format(date.getTime());
File mediaFile;
if(type == MEDIA_TYPE_VIDEO) {
// For unique video file name appending current timeStamp with file name
mediaFile = new File(mediaStorageDir.getPath() + File.separator + slpid + "_" + pwsid + "_" + timeStamp + ".mp4");
}
else if(type == MEDIA_TYPE_AUDIO) {
// For unique video file name appending current timeStamp with file name
mediaFile = new File(mediaStorageDir.getPath() + File.separator + slpid + "_" + pwsid + "_" + timeStamp + ".3gp");
} else {
return null;
}
return mediaFile;
}
/** Create a file Uri for saving an image or video
* #throws Exception */
private Uri getOutputMediaFileUri(int type) throws Exception{
return Uri.fromFile(getOutputMediaFile(type));
}
//usage:
try {
file=getOutputMediaFileUri(MEDIA_TYPE_AUDIO).getPath();
} catch (Exception e1) {
e1.printStackTrace();
return;
}
This code is Working great & Worked on KitKat as well. Appreciate #RajaReddy PolamReddy
Added few more steps here and also Visible on Gallery as well.
public void SaveOnClick(View v){
File mainfile;
String fpath;
try {
//i.e v2:My view to save on own folder
v2.setDrawingCacheEnabled(true);
//Your final bitmap according to my code.
bitmap_tmp = v2.getDrawingCache();
File(getExternalFilesDir(Environment.DIRECTORY_PICTURES)+File.separator+"/MyFolder");
Random random=new Random();
int ii=100000;
ii=random.nextInt(ii);
String fname="MyPic_"+ ii + ".jpg";
File direct = new File(Environment.getExternalStorageDirectory() + "/MyFolder");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/MyFolder/");
wallpaperDirectory.mkdirs();
}
mainfile = new File(new File("/sdcard/MyFolder/"), fname);
if (mainfile.exists()) {
mainfile.delete();
}
FileOutputStream fileOutputStream;
fileOutputStream = new FileOutputStream(mainfile);
bitmap_tmp.compress(CompressFormat.JPEG, 100, fileOutputStream);
Toast.makeText(MyActivity.this.getApplicationContext(), "Saved in Gallery..", Toast.LENGTH_LONG).show();
fileOutputStream.flush();
fileOutputStream.close();
fpath=mainfile.toString();
galleryAddPic(fpath);
} catch(FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is Media scanner to Visible in Gallery.
private void galleryAddPic(String fpath) {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(fpath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
Click Here for full description and source code
public void saveImage(Context mContext, Bitmap bitmapImage) {
File sampleDir = new File(Environment.getExternalStorageDirectory() + "/" + "ApplicationName");
TextView tvImageLocation = (TextView) findViewById(R.id.tvImageLocation);
tvImageLocation.setText("Image Store At : " + sampleDir);
if (!sampleDir.exists()) {
createpathForImage(mContext, bitmapImage, sampleDir);
} else {
createpathForImage(mContext, bitmapImage, sampleDir);
}
}

Categories

Resources