public String getVideoFilePath() {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath() + "/" + System.currentTimeMillis() + "compress.mp4";
}
public static void exportMp4ToGallery(Context context, String filePath) {
File file = new File(filePath);
MediaScannerConnection.scanFile(context, new String[]{file.toString()}, null, null);
}
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29"/>
android:requestLegacyExternalStorage="true"
Currently, I'm using the above approach. getVideoFilePath() will return a path to the compressor class after compression is successful it will call exportMp4ToGallery(Context context, String filePath).
Is it a good approach? or Should I use MediaStore.video. But I want to know how to do the same with mediaStore.Video. Please help if you know, please provide a code snnipet.
EDIT ANOTHER APPROACH IS:
private String getFileName() {
String path = getExternalFilesDir("TrimmedVideo").getPath();
Calendar calender = Calendar.getInstance();
String fileDateTime = calender.get(Calendar.YEAR) + "_" +
calender.get(Calendar.MONTH) + "_" +
calender.get(Calendar.DAY_OF_MONTH) + "_" +
calender.get(Calendar.HOUR_OF_DAY) + "_" +
calender.get(Calendar.MINUTE) + "_" +
calender.get(Calendar.SECOND);
String fName = "trimmed_video_";
File newFile = new File(path + File.separator +
(fName) + fileDateTime + "." + TrimmerUtils.getFileExtension(this, uri));
return String.valueOf(newFile);
}
This above code will give the compressor class a path to save it in app external directory and then copy that file to gallery using MediaStore like below:
public Uri addVideo(String videoFilePath) {
Uri uriSavedVideo;
File createdvideo = null;
ContentResolver resolver = getContentResolver();
String videoFileName = "video_" + System.currentTimeMillis() + ".mp4";
ContentValues valuesvideos;
valuesvideos = new ContentValues();
if (Build.VERSION.SDK_INT >= 29) {
valuesvideos.put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/" + "Folder");
valuesvideos.put(MediaStore.Video.Media.TITLE, videoFileName);
valuesvideos.put(MediaStore.Video.Media.DISPLAY_NAME, videoFileName);
valuesvideos.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
valuesvideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
Uri collection = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
uriSavedVideo = resolver.insert(collection, valuesvideos);
} else {
String directory = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + Environment.DIRECTORY_MOVIES + "/" + "YourFolder";
createdvideo = new File(directory, videoFileName);
valuesvideos.put(MediaStore.Video.Media.TITLE, videoFileName);
valuesvideos.put(MediaStore.Video.Media.DISPLAY_NAME, videoFileName);
valuesvideos.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
valuesvideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
valuesvideos.put(MediaStore.Video.Media.DATA, createdvideo.getAbsolutePath());
uriSavedVideo = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, valuesvideos);
}
if (Build.VERSION.SDK_INT >= 29) {
valuesvideos.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis());
valuesvideos.put(MediaStore.Video.Media.IS_PENDING, 1);
}
ParcelFileDescriptor pfd;
try {
pfd = getContentResolver().openFileDescriptor(uriSavedVideo, "w");
FileOutputStream out = new FileOutputStream(pfd.getFileDescriptor());
File videoFile = new File(videoFilePath);
FileInputStream in = new FileInputStream(videoFile);
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
pfd.close();
} catch (Exception e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= 29) {
valuesvideos.clear();
valuesvideos.put(MediaStore.Video.Media.IS_PENDING, 0);
getContentResolver().update(uriSavedVideo, valuesvideos, null, null);
}
return uriSavedVideo;
}
Related
As per the restrictions of Android Q and above, I am trying to download the video file in Downloads folder under folder. But It always takes to the Android/data/<package_name>/Downloads/ folder. minSdk for my app is API 16, and currently targetSdk is API 29.
Below is reference code snippet used.
String videoFileName = "video_" + System.currentTimeMillis() + ".mp4";
ContentValues valuesvideos;
valuesvideos = new ContentValues();
valuesvideos.put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/" + "Folder");
valuesvideos.put(MediaStore.Video.Media.TITLE, videoFileName);
valuesvideos.put(MediaStore.Video.Media.DISPLAY_NAME, videoFileName);
valuesvideos.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
valuesvideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
valuesvideos.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis());
valuesvideos.put(MediaStore.Video.Media.IS_PENDING, 1);
ContentResolver resolver = mContext.getContentResolver();
Uri collection = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
Uri uriSavedVideo = resolver.insert(collection, valuesvideos);
ParcelFileDescriptor pfd;
try {
pfd = mContext.getContentResolver().openFileDescriptor(uriSavedVideo, "w");
FileOutputStream out = new FileOutputStream(pfd.getFileDescriptor());
File storageDir = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_MOVIES), "Folder");
File imageFile = new File(storageDir, "Myvideo");
FileInputStream in = new FileInputStream(imageFile);
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
pfd.close();
} catch (Exception e) {
e.printStackTrace();
}
valuesvideos.clear();
valuesvideos.put(MediaStore.Video.Media.IS_PENDING, 0);
mContext.getContentResolver().update(uriSavedVideo, valuesvideos, null, null);
Thank You in Advance.
This is the current code I have to store videos generated by my app on disk. I want this videos to be accessible by other apps like TikTok, WhatsApp and google Photos. I also want to create my own gallery inside my app. However, the files saved by approach below do not show up on TikTok. They show up under Google photos Library\Movies folder, which users have to really dig deep to find.
How to make these files accessible to all apps? how can I write my own video gallery to just show files created by my app?
private void addVideoToGallery(File videoFile) {
Uri uriSavedVideo;
File createdvideo = null;
ContentResolver resolver = activity.getContentResolver();
String path = videoFile.getAbsolutePath();
String videoFileName = path.substring(path.lastIndexOf("/") + 1);
ContentValues valuesvideos;
valuesvideos = new ContentValues();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
valuesvideos.put(MediaStore.Video.Media.RELATIVE_PATH, Environment.DIRECTORY_MOVIES + File.pathSeparator + activity.getString(R.string.app_name));
valuesvideos.put(MediaStore.Video.Media.TITLE, videoFileName);
valuesvideos.put(MediaStore.Video.Media.DISPLAY_NAME, videoFileName);
valuesvideos.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
valuesvideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
Uri collection = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
uriSavedVideo = resolver.insert(collection, valuesvideos);
} else {
String directory = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + Environment.DIRECTORY_MOVIES;
createdvideo = new File(directory, videoFileName);
valuesvideos.put(MediaStore.Video.Media.TITLE, videoFileName);
valuesvideos.put(MediaStore.Video.Media.DISPLAY_NAME, videoFileName);
valuesvideos.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
valuesvideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
valuesvideos.put(MediaStore.Video.Media.DATA, createdvideo.getAbsolutePath());
uriSavedVideo = resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, valuesvideos);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
valuesvideos.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis());
valuesvideos.put(MediaStore.Video.Media.IS_PENDING, 1);
}
ParcelFileDescriptor pfd;
try {
pfd = resolver.openFileDescriptor(uriSavedVideo, "w");
FileOutputStream out = new FileOutputStream(pfd.getFileDescriptor());
FileInputStream in = new FileInputStream(videoFile);
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
pfd.close();
} catch (Exception e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
valuesvideos.clear();
valuesvideos.put(MediaStore.Video.Media.IS_PENDING, 0);
resolver.update(uriSavedVideo, valuesvideos, null, null);
}
}
This code cannot access the same files from my app using code below.
private void getVids(){
List<Video> videoList = new ArrayList<Video>();
Uri collection;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
collection = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
} else {
collection = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
}
String[] projection = new String[] {
MediaStore.Video.Media._ID,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DURATION,
MediaStore.Video.Media.SIZE
};
String selection = MediaStore.Video.Media.DURATION +
" >= ?";
String[] selectionArgs = new String[] {
String.valueOf(TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES))};
String sortOrder = MediaStore.Video.Media.DISPLAY_NAME + " ASC";
try (Cursor cursor = activity.getContentResolver().query(
collection,
projection,
selection,
selectionArgs,
sortOrder
)) {
// Cache column indices.
int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
int nameColumn =
cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
int durationColumn =
cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION);
int sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
while (cursor.moveToNext()) {
// Get values of columns for a given video.
long id = cursor.getLong(idColumn);
String name = cursor.getString(nameColumn);
int duration = cursor.getInt(durationColumn);
int size = cursor.getInt(sizeColumn);
Uri contentUri = ContentUris.withAppendedId(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id);
// Stores column values and the contentUri in a local object
// that represents the media file.
videoList.add(new Video(contentUri, name, duration, size));
}
}
}
Now I copy mp4 file from external storage folder and save copy file in gallery with folder. But My gallery app doesn't have folder I code. Surely, File too. But In File Browser, There are exists correctly in DCIM folder.
So, How can I save file in gallery with folder that I code. Please let me know If you can solve this issue.
private void saveToGallery(String recVideoPath) {
progressdialog = new CNetProgressdialog(this);
progressdialog.show();
String folderName = "DuetStar";
String fromPath = recVideoPath;
String toPath = Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DCIM;
File toPathDir = new File(toPath + "/" + folderName);
final File fromPathFile = new File(fromPath);
File toPathFile = new File(toPath + "/" + folderName, recVideoPath.substring(recVideoPath.lastIndexOf("/") + 1, recVideoPath.length()));
Log.d(TAG, "saveToGallery: " + RecordActivity.currentCreateFileName);
Log.d(TAG, "saveToGallery: " + toPathDir.toString());
Log.d(TAG, "saveToGallery: " + fromPath.toString());
Log.d(TAG, "saveToGallery: " + toPath.toString());
if (!toPathDir.exists()) {
toPathDir.mkdir();
} else {
}
FileInputStream fis = null;
FileOutputStream fos = null;
try {
if (toPathDir.exists()) {
fis = new FileInputStream(fromPathFile);
fos = new FileOutputStream(toPathFile);
byte[] byteArray = new byte[1024];
int readInt = 0;
while ((readInt = fis.read(byteArray)) > 0) {
fos.write(byteArray, 0, readInt);
}
Log.d(TAG, "saveToGallery: " + readInt);
fis.close();
fos.close();
Log.d(TAG, "saveToGallery: " + "Seucceful");
} else {
Toast.makeText(this, "There is no directory", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.getMessage();
}
progressdialog.dismiss();
}
You can save in specific folder as you wish see this code snippet for idea
String extStorageDirectory;
extStorageDirectory = Environment.getExternalStorageDirectory().toString() + "/Video Folder name/";
//making the folder
new File(extStorageDirectory).mkdirs();
I have 20k image files in a folder inside my local storage, I need to display the image by its file name from local storage. How to do it? I attached my code here:
if (Environment.getExternalStorageState()
.equals(Environment.DIRECTORY_PICTURES)) {
String filePath = File.separator + "sdcard" + File.separator + "Android" + File.separator + "obb" + File.separator + "convertMp3ToDb" + File.separator + "ldoce6pics" + File.separator + fileName;
try {
FileInputStream fis = new FileInputStream(filePath);
String entry = null;
while ((entry = fis.toString()) != null) {
if (!entry.toString().isEmpty()) {
File Mytemp = File.createTempFile("TCL", "jpg", getContext().getCacheDir());
Mytemp.deleteOnExit();
FileOutputStream fos = new FileOutputStream(Mytemp);
for (int c = fis.read(); c != -1; c = fis.read()) {
try {
fos.write(c);
} catch (IOException e) {
e.printStackTrace();
}
}
fos.close();
FileInputStream MyFile = new FileInputStream(Mytemp);
final Bitmap bit = BitmapFactory.decodeStream(MyFile);
imageView.setImageBitmap(bit);
}
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (Environment.getExternalStorageState()
.equals(Environment.DIRECTORY_PICTURES)) {
String filePath = File.separator + "sdcard" + File.separator + "Android" + File.separator + "obb" + File.separator + "convertMp3ToDb" + File.separator + "ldoce6pics" + File.separator + fileName;
File f = new File(filePath);
if(f.exits()){
Bitmap bm = BitmapFactory.decodeFile(f.getAbsolutePath());
imageView.setImageBitmap(bm);
}else{
// invalid path
}
}
}
Update Section:
if (Environment.getExternalStorageState()
.equals(Environment.DIRECTORY_PICTURES)) {
// this never be true see below image
}
You have to do like this
File file = new File(Environment.getExternalStorageState()+"/Android/obb/convertMp3ToDb/ldoce6pics/"+fileName);
if (file.exists()) {
// your condition should ne likr this.
}
I am new to android. I am capturing video using following code:
final int REQUEST_VIDEO_CAPTURED = 1;
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
String imagepath = Environment.getExternalStorageDirectory() + "/"
+ galleryStart + "/" + FolderName + "/" + ts + ".mp4";
File file = new File(imagepath);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,outputFileUri);
startActivityForResult(intent, REQUEST_VIDEO_CAPTURED);
If I haven't set path its work fine other wise it gives me error." unfortunately camera has stopped working." I am setting path for saving the videos in particular directory.
Camera App Doesn't make you dir which you asked for in your Uri. So try to make it first.
String imagepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + galleryStart + "/" + FolderName + "/" + ts + ".mp4";
File file = new File(imagepath);
try
{
if(file.exists() == false)
{
file.getParentFile().mkdirs();
file.createNewFile();
}
}
catch (IOException e)
{
Log.e(TAG, "Could not create file.", e);
}
Uri outputFileUri = Uri.fromFile(file);
Hope it helps you out!!