Download video in Downloads folder Android Q - android

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.

Related

How to save video to gallery using mediaStore.Video android?

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;
}

How can I read an image from an android phone directory, rename it, and copy back to the same directory?

The piece of code I have written so far is as follow:
String fname = type + (i + 1) + "-" + ext;
String fname1 = type + (i + 2) + "-" + System.currentTimeMillis() + ext;
File file = new File(myDir, fname);
if (file.exists()) {
//file.delete();
continue;
} else {
try {
InputStream in = getResources().openRawResource(x);
FileOutputStream outStream = new FileOutputStream(file);
byte[] buff = new byte[1024];
byte[] buff1 = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
outStream.write(buff, 0, read);
//I wanted to fasten up the process so i added the code below: I have tried multiple way to do the same
//FileInputStream fi = new FileInputStream(myDir+File.separator+fname);
File File1 = new File(Environment.getExternalStorageDirectory()+File.separator +
"Application"+File.separator + "/Images" + "Image1-.jpg");
File File2 = new File(Environment.getExternalStorageDirectory()+File.separator + "Application"+File.separator + "/Images" + fname1);
//String name = in1.getName();
File newname = new File(fname1);
File1.renameTo(newname);
FileUtils.copyDirectory(File1, File2);
}
finally {
in.close();
outStream.close();
}
However, this does not work.
Can anyone give me some advice on how to fix this?
You can read images from directory by this-
file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
call copyBack() function and pass file path and Name
String shiftedPath = copyBack(file.getAbsolutePath(),newName);
// function use for copy and rename
public String copyBack(String srcPath,String newName) {
//you can defined path of same directory as per your requirement, and just pass new
file = new File(Environment.getExternalStorageDirectory() + File.separator + "newName");
file.mkdirs();
try {
// File sd = Environment.getExternalStorageDirectory();
// File data = Environment.getDataDirectory();
String sourceImagePath = srcPath;
String destinationImagePath = file.getAbsolutePath();
File source = new File(sourceImagePath);
destination = new File(file, ".image");
if (source.exists()) {
FileChannel src = new FileInputStream(source).getChannel();
FileChannel dst = new FileOutputStream(destination).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return destination.getAbsolutePath();
}

Xamarin Android - Setting ringtone from mp3 in asset folder

I am using Xamarin Forms and using Dependency Service to set ringtone from mp3 places in asset folder. Here is my code:
AssetManager assets = Forms.Context.Assets;
fileName = "Artist.mp3";
System.IO.Stream inputStream;
System.IO.Stream outputStream;
try
{
inputStream = assets.Open("Sounds/" + fileName);
**_ outputStream = Forms.Context.OpenFileOutput(fileName, FileCreationMode.Private); _**
byte[] buffer = new byte[65536 * 2];
int read;
while ((read = inputStream.Read(buffer, 0, (int)inputStream.Length)) != -1)
{
outputStream.Write(buffer, 0, read);
}
inputStream.Close();
inputStream = null;
outputStream.Flush();
outputStream.Close();
outputStream = null;
Java.IO.File newSoundFile = new Java.IO.File(basepath + "/Sounds/" + fileName);
if (newSoundFile.Exists())
{
ContentValues values = new ContentValues();
values.Put(MediaStore.MediaColumns.Data, newSoundFile.AbsolutePath);
values.Put(MediaStore.MediaColumns.Title, "Test Ringtone");
values.Put(MediaStore.MediaColumns.MimeType, "audio/*");
values.Put(MediaStore.MediaColumns.Size, newSoundFile.Length());
values.Put(MediaStore.Audio.Media.InterfaceConsts.Artist, "Artist MP3");
values.Put(MediaStore.Audio.Media.InterfaceConsts.Duration, 2300);
values.Put(MediaStore.Audio.Media.InterfaceConsts.IsRingtone, true);
values.Put(MediaStore.Audio.Media.InterfaceConsts.IsNotification, false);
values.Put(MediaStore.Audio.Media.InterfaceConsts.IsAlarm, false);
values.Put(MediaStore.Audio.Media.InterfaceConsts.IsMusic, false);
Android.Net.Uri uri = MediaStore.Audio.Media.GetContentUriForPath(newSoundFile.AbsolutePath);
Forms.Context.ContentResolver.Delete(uri, MediaStore.MediaColumns.Data + "=\"" + newSoundFile.AbsolutePath + "\"", null);
Android.Net.Uri newUri = Forms.Context.ContentResolver.Insert(uri, values);
try
{
RingtoneManager.SetActualDefaultRingtoneUri(Forms.Context, RingtoneType.Ringtone, newUri);
}
catch (Exception e)
{
}
}
}
catch (Exception e)
{
}
I am getting below exception in the line outputStream = Forms.Context.OpenFileOutput(fileName, FileCreationMode.Private)
System.NotSupportedException: Specified method is not supported.
at Android.Runtime.InputStreamInvoker.get_Length () [0x00000] in /Users/builder/data/lanes/3053/a94a03b5/source/monodroid/src/Mono.Android/src/Runtime/InputStreamInvoker.cs:55
You are implementing Stream.CopyTo manually. Just use it.
using (var inputStream = assets.Open("Sounds/" + fileName))
using (var outputStream = Forms.Context.OpenFileOutput(fileName, FileCreationMode.Private))
{
inputStream.CopyTo(outputStream);
}

How to save audio file from raw folder to phone

Below I have the coding for hiow to set audio as your ringtone. This works fine however I wanna know how could I alter this such that it well save just the audio so that it can be played with my other songs
public boolean save1(int type) {
byte[] buffer = null;
InputStream fIn = getBaseContext().getResources().openRawResource(
R.raw.song);
int size = 0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
return false;
}
String path = Environment.getExternalStorageDirectory().getPath()
+ "/media/audio/";
String filename = "New song";
FileOutputStream save;
try {
save = new FileOutputStream(path + filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.parse("file://" + path + filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, filename);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
if (RingtoneManager.TYPE_RINGTONE == type) {
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
} else if (RingtoneManager.TYPE_NOTIFICATION == type) {
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
} else if (RingtoneManager.TYPE_ALARM == type) {
values.put(MediaStore.Audio.Media.IS_ALARM, true);
}
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k
.getAbsolutePath());
Uri newUri = MainActivity.this.getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(MainActivity.this, type,
newUri);
this.getContentResolver()
.insert(MediaStore.Audio.Media.getContentUriForPath(k
.getAbsolutePath()), values);
return true;
}
To move raw folder file to sdcard or phone storage below code will work:
private void CopyRAWtoPhone(int id, String path) throws IOException {
InputStream in = getResources().openRawResource(id);
FileOutputStream out = new FileOutputStream(path);
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
}
where first Variable id will be your raw file id and String path will be your phone storage path.

How to set custom Alarm tone in android

I need to set custom alarm tone in my App. Could anyone please just tell me how to set custom ringtone or Mp3 as an alarm ? Any kind of help will be appreciated.
Here is also a solution for this problem
setting audio file as Ringtone
Best,
Shahzad Majeed
You can use audio player to play your mp3.But here is a better alarm app which fulfills your requirements.
http://code.google.com/p/kraigsandroid/source/browse/#git%2Fandroid%2Falarmclock%2Fsrc%2Fcom%2Fangrydoughnuts%2Fandroid%2Falarmclock
in the Android docs look at the Status Bar Notifications page. In particular see the Adding a Sound section.
Try this
add any .mp3 file in raw folder place name of that file
public void setAlarm() {
File file = new File(Environment.getExternalStorageDirectory(),
"/Your Directory Name");
if (!file.exists()) {
file.mkdirs();
}
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Your Directory Name";
File f = new File(path + "/", filename + ".mp3");
Uri mUri = Uri.parse("android.resource://" + getContext().getPackageName() + "/raw/" + filename);
ContentResolver mCr = getContext().getContentResolver();
AssetFileDescriptor soundFile;
try {
soundFile = mCr.openAssetFileDescriptor(mUri, "r");
} catch (FileNotFoundException e) {
soundFile = null;
}
try {
byte[] readData = new byte[1024];
FileInputStream fis = soundFile.createInputStream();
FileOutputStream fos = new FileOutputStream(f);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, f.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, filename);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.MediaColumns.SIZE, f.length());
values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(f.getAbsolutePath());
getContext().getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + f.getAbsolutePath() + "\"", null);
Uri newUri = mCr.insert(uri, values);
try {
RingtoneManager.setActualDefaultRingtoneUri(getContext(),
RingtoneManager.TYPE_ALARM, newUri);
Settings.System.putString(mCr, Settings.System.ALARM_ALERT,
newUri.toString());
Toast.makeText(getContext(), "Done", Toast.LENGTH_SHORT).show();
} catch (Throwable t) {
}
}

Categories

Resources