Am trying to insert an aduio file in the android phone. the same code works fin in android
2.1
but when i try to use it in Android 2.2; the inserting in ContentResolver succseed but i can't
find my audio file in the gallery (so the user can't see it)
context.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.Audio.Media.DATA, k.getAbsolutePath());
values.put(MediaStore.Audio.Media.TITLE, aud.TITLE);
values.put(MediaStore.Audio.Media.MIME_TYPE, aud.MIME_TYPE);
values.put(MediaStore.Audio.Media.ARTIST, aud.ARTIST);
values.put(MediaStore.Audio.Media.IS_RINGTONE, aud.IS_RINGTONE);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, aud.IS_NOTIFICATION);
values.put(MediaStore.Audio.Media.IS_ALARM, aud.IS_ALARM);
values.put(MediaStore.Audio.Media.IS_MUSIC, aud.IS_MUSIC);
//Insert it into the database
context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
Try adding "file:///" that will work
Related
I'm trying to add some mp3 files from assets folder to android system sounds notification.
My problems are:
To add sound from assets to system sound I needed to storage permission with following code:
fun addSounds() {
val file = File(requireContext().filesDir, "notifications")
if (!file.exists())
file.mkdirs()
val soundFile = File(file.absolutePath + "/" + "longbeep.mp3")
requireContext().assets.open("long_beep.mp3").use { input ->
soundFile.outputStream().use { output ->
input.copyTo(output, 1024)
}
}
registerFile(soundFile, "ShahramLong2")
}
private fun registerFile(file: File, fileName: String) {
val values = ContentValues()
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, fileName);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
val generalaudiouri = Media.EXTERNAL_CONTENT_URI
val uri = Media.getContentUriForPath(file.absolutePath)
requireContext().contentResolver.delete(
Media.EXTERNAL_CONTENT_URI,
MediaStore.MediaColumns.DATA + "='" + file.getAbsolutePath() + "'",
null
)
requireContext().contentResolver.insert(Media.EXTERNAL_CONTENT_URI, values)
}
When changed registerFile to following code app crashed with exception
Caused by: java.lang.UnsupportedOperationException: Writing to internal storage is not supported.
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:174)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:142)
Code is:
private fun registerFile(file: File, fileName: String) {
val values = ContentValues()
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, fileName);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
val generalaudiouri = Media.EXTERNAL_CONTENT_URI
val uri = Media.getContentUriForPath(file.absolutePath)
// use uri instead of Media.EXTERNAL_CONTENT_URI
requireContext().contentResolver.delete(
uri!!,
MediaStore.MediaColumns.DATA + "='" + file.getAbsolutePath() + "'",
null
)
requireContext().contentResolver.insert(uri!!, values)
}
Another problem is apparently this line does not work:
requireContext().contentResolver.delete(
Media.EXTERNAL_CONTENT_URI,
MediaStore.MediaColumns.DATA + "='" + file.getAbsolutePath() + "'",
null
)
The sound is added several times.
As getExternalStoragePublicDirectory has been deprecated in Android Q and recommendation is to use MediaStore API
Here is my Image URL https://cdn.pixabay.com/photo/2020/04/21/06/41/bulldog-5071407_1280.jpg
I want to download this image file and want to save the shared folder i.e. Downloads or Pictures Folder as per MediaStore API
Below is the sample code
ContentResolver resolver = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
Note: compileSdkVersion 30
I want an example of How to download an Image/Video file in Android R and save it into the download folder location with MediaStore.
In order to save it on android 10. Then after calling the insert method you will get the URI then call
os = getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.close();
In Android 10 calling insert method is not enough
Your code will look like this
ContentResolver resolver = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
OutputStream os = getContentResolver().openOutputStream(uri);
Bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.close();
Hi Kanaiya I answered an improvement on MediaStore answer MediaStore.Images.Media.insertImage deprecated
I did use workManager and viewModel not sure if that would apply to your use-case, I did test my answer on API 26 and on API 30.
My working sample is just a 2018 workmanager codelab for which I made minor changes to remove a depreciated api call, thanks for the original idea commonsware
I want my app to set a ringtone. The user has selected one from the existing library entries before using the system picker and gets this extra back: RingtoneManager.EXTRA_RINGTONE_PICKED_URI
In this example I have picked "Andromeda" from the default ringtones and get this path: content://media/internal/audio/media/103
When I try to set it at a given time I run this code:
Uri ur = Uri.parse(ringtoneFile.getAbsolutePath()); RingtoneManager.setActualDefaultRingtoneUri(context, ringtoneType, uri);
I have also tried this version:
Uri ur = Uri.parse(ringtoneFile.getAbsolutePath()); android.provider.Settings.System.putString(context.getContentResolver(), android.provider.Settings.System.RINGTONE, uri.toString());
Neither works. The system's sound settings will look like this:
Only 103 is shown, not "Andromeda" as I would expect. When I have the emulator called it just makes a ding sound, so it probably can't play the desired file and uses some fallback one.
There are plenty of examples here where people pick a custom file from the filesystem and add that to the library anew using "ContentValues". But I do not want to add anything myself, I just want to set one from the default ringtones.
As an alternative I have tried to code as well. It does add an additional entry to the library. Unfortunately old ones are not deleted, but pile up. Also I get the same ding sound when calling the emulator, not the one I selected.
private boolean applyRingTone(File ringtoneFile, int ringtoneType, Context context)
{
Miscellaneous.logEvent("i", "Profile", "Request to set ringtone to " + ringtoneFile.getAbsolutePath(), 3);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, ringtoneFile.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, context.getResources().getString(R.string.app_name) + " ringtone");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
values.put(MediaStore.MediaColumns.SIZE, ringtoneFile.length());
values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
values.put(MediaStore.Audio.Media.IS_RINGTONE, ringtoneType == RingtoneManager.TYPE_RINGTONE);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, ringtoneType == RingtoneManager.TYPE_NOTIFICATION);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
Uri ur = MediaStore.Audio.Media.getContentUriForPath(ringtoneFile.getAbsolutePath());
context.getContentResolver().delete(ur, MediaStore.MediaColumns.DATA + "=\"" + ringtoneFile.getAbsolutePath() + "\"", null);
Uri uri = context.getContentResolver().insert(ur, values);
try
{
RingtoneManager.setActualDefaultRingtoneUri(context, ringtoneType, uri);
Miscellaneous.logEvent("i", "Profile", "Ringtone set to: " + uri.toString(), 1);
return true;
}
catch (Throwable t)
{
String message = "Error setting ringtone: " + Log.getStackTraceString(t);
Miscellaneous.logEvent("e", "Profile", message, 1);
}
return false;
}
I haven't quite solved my problem, yet, but at least spotted the culprit.
The way to set the file as ringtone does work. However the path of the source file is incorrect. That is pretty weird because it is determined by using a filepicker:
Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT);
fileIntent.setType("audio/*");
startActivityForResult(Intent.createChooser(fileIntent, "Select a ringtone"), intentCodeRingtonePickerCallsFile);
This returns as path:
content://com.android.externalstorage.documents/document/primary%3AMusic%2Fmusicfile.mp3
After converting it to a File object it'll become
/document/primary%3AMusic%2F04.%20Elevator%20Girl.mp3
When just hard-coding the path into the sourcecode (in a format a regular Linux user would assume it needs to have) it is actually simply:
/sdcard/Music/musicfile.mp3
And that works flawlessly. I'll have to figure out how to correctly determine the path, but the method to set a file as ringtone is functional.
UPDATE: I have an answer to my path problem: Get Real Path For Uri Android
I am developing an android application in which there is a scenario that we need to convert a file's absolute path (/storage/emulated/0/..../1584362593949.pdf) to content URI(content://)
I have tried converting for the file types such as Audio and video with the help of content resolver and there was no issue I faced but stuck at converting for PDF documents.
Check the code snippet below
public Uri convertFileUriToContentUri(String filePath, String title) {
String fileType = title.substring(title.lastIndexOf(".") + 1);
File file = new File(filePath);
Uri base = null;
//creating content values of size 4
ContentValues values = new ContentValues(4);
long current = System.currentTimeMillis();
switch (fileType) {
case "mp3":
values.put(MediaStore.Audio.Media.TITLE, "audio" + file.getName());
values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.DATA, file.getAbsolutePath());
base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
break;
case "pdf":
// I am Stuck here as MediaStore does not provide support to documents
break;
case "mp4":
values.put(MediaStore.Video.Media.TITLE, "video" + file.getName());
values.put(MediaStore.Video.Media.DATE_ADDED, (int) (current / 1000));
values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
values.put(MediaStore.Video.Media.DATA, file.getAbsolutePath());
base = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
break;
}
//creating content resolver and storing it in the external content uri
ContentResolver contentResolver = context.getContentResolver();
Uri newUri = contentResolver.insert(base, values);
//sending broadcast message to scan the media file so that it can be available
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri));
return newUri;
}
Please help me find out the solution.
i am new to android, i copied files to /storage/sdcard1 from host pc using adb push.
But unable to view the file from gallery application.It is showing through ls command and when i rebooted the device , gallery application showing files properly.But immediately it is not updating in gallery , so can any one help me out for this?
Thanks in advance
You'll have to notify the media scanner to capture metadata of the newly created files. Apps like Gallery work on the metadata database and not directly on the filesystem.
Programmatically you'd use MediaScannerConnection.
Since you're working with adb, you can send a broadcast to invoke media scanner.
Media scanner runs as part of the boot sequence so that's why it works after reboot.
Because your gallery DB isn't updated.
You can run media scanner manually
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
or Use
MediaStore.Images.Media.insertImage();
You can also insert gallery(media) DB by hand.
private Uri insertMediaStore(String dirPath, String filename, byte[] jpegByteArray) {
String filePath = dirPath + "/" + filename;
try {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, new Date().getTime());
values.put(Images.Media.ORIENTATION, "0");
String title = filename.replace(".jpg", "");
values.put(Images.Media.TITLE, title);
values.put(Images.Media.DISPLAY_NAME, filename);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.SIZE, jpegByteArray.length);
values.put("_data", filePath);
Uri uri = getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
OutputStream os = getContentResolver().openOutputStream(uri);
os.write(jpegByteArray);
os.close();
Logger.info("MediaStore Inserted URI:" + uri.toString());
return uri;
} catch(Exception ex) {
Logger.error(ex, "Failed to save the Bitmap file. FilePath: %s", filePath);
}
return null;
}
code reference: http://helloworld.naver.com/helloworld/1819