No media scanner android

No media scanner android

Для функционирования программы необходимы права root пользователя.

Краткое описание:
Это приложение будет обновлять данные MediaStorage на устройстве.

Описание:
Это приложение является одним из приложений, обычно называемых медиа-сканером.

Если вы не можете увидеть или найти фотографии, мультимедийные файлы (музыку, видео), а также другие файлы на вашем устройстве, вы можете решить эту проблему с помощью этого приложения.

Она имеет следующие особенности.
* Вы можете сканировать быстро все файлы (медиа-файлы, файлы документов и другие) на вашем устройстве.
* Это обновить mediaStorage информацию.
* Если вы в беде не видит файлы в устройстве, вы можете решить эту проблему с помощью этого инструмента
* Вы можете сканировать на внутренней памяти и внешней Strage (SD-карты).
* Вы можете выбрать простое сканирование (все папки) или выдвинутое сканирование (только выбранные каталоги).
* Вы можете найти фотографии, мультимедийные файлы (музыку, видео), а также другие файлы на устройстве снова.

* Вы можете открыть легко «Media Storage» приложение informaion вид.

* Это правильно работать даже с Android 4.4 (Kitkat), android5.0 (Lolipop) и android6.0 (Зефир).

Требуется Android: 2.3 до 7.0
Русский интерфейс: Есть.

Разработчик: Hiroyuki Mizuhara
Домашняя страница: тут
Google Play:
Видео YouTube: Нет.

Источник

No media scanner android

Для функционирования программы необходимы права root пользователя.

Краткое описание:
Это приложение будет обновлять данные MediaStorage на устройстве.

Описание:
Это приложение является одним из приложений, обычно называемых медиа-сканером.

Если вы не можете увидеть или найти фотографии, мультимедийные файлы (музыку, видео), а также другие файлы на вашем устройстве, вы можете решить эту проблему с помощью этого приложения.

Она имеет следующие особенности.
* Вы можете сканировать быстро все файлы (медиа-файлы, файлы документов и другие) на вашем устройстве.
* Это обновить mediaStorage информацию.
* Если вы в беде не видит файлы в устройстве, вы можете решить эту проблему с помощью этого инструмента
* Вы можете сканировать на внутренней памяти и внешней Strage (SD-карты).
* Вы можете выбрать простое сканирование (все папки) или выдвинутое сканирование (только выбранные каталоги).
* Вы можете найти фотографии, мультимедийные файлы (музыку, видео), а также другие файлы на устройстве снова.

* Вы можете открыть легко «Media Storage» приложение informaion вид.

* Это правильно работать даже с Android 4.4 (Kitkat), android5.0 (Lolipop) и android6.0 (Зефир).

Требуется Android: 2.3 до 7.0
Русский интерфейс: Есть.

Разработчик: Hiroyuki Mizuhara
Домашняя страница: тут
Google Play:
Видео YouTube: Нет.

Источник

Media scanner for secondary storage on Android Q

With the newer Android Q many things changed, especially with scoped storage and gradual deprecation of file:/// URIs. The problem is the lack of documentation on how to handle media files correctly on Android Q devices.

I have a media file (audio) management application and I could not find yet a reliable way to tell to the OS that I performed a change to a file so that it can update its MediaStore record.

Option #1: MediaScannerService

  • Works with file:// URIs from primary storage
  • Not works with file:// URIs from secondary storage (such as removable storage)
  • Not works with any content:// URI

Option #2: broadcast

  • Not working at all
  • Soon deprecated

Option #3: manual MediaStore insertion

AudioFileContentValues are some column values from MediaStore.Audio.AudioColumns .

Old method based on file:// URI:

  • MediaStore.Audio.Media.getContentUriForPath is deprecated
  • Still not working

Newer method based on what I could put together from documentation:

Where correctVolume would be external from primary storage, while it would be something like 0000-0000 for secondary storage, depending on where the file is located.

  • Insertion returns a content URI such as content://media/external/audio/media/125 but then no record is persisted inside MediaStore for files located in primary storage
  • Insertion fails with no URI returned and no record in MediaStore
Читайте также:  Figma templates android free

These are more or less all the methods available in previous Android versions but none of them now allow me to notify the system that I changed some audio file metadata and to get Android to update MediaStore records. Event though option #1 is partially working, this could never be a valuable solution because it’s clearly not supporting content URIs.

Is there any reliable way to trigger media scan on Android Q, despite where the file is located? We shouldn’t even care about file location, according to Google, since we will soon only use content URIs. MediaStore has always been a little frustrating in my opinion, but now the situation is pretty worse.

1 Answer 1

I’m also currently struggling with that.

I think what you want to do you cannot do any longer once you are on Android Q, because you are not allowed to access the Music directory on Q. You are only allowed to create and access files in directories you created. You did not create the music directory.

Now every change to the Media has to happen threw the MediaStore. So you insert your Music file beforehand and then get an outputstream from the MediaStore to write to it. All the changes on Q on Media should be done threw the MediaStore hence you informing the MediaStore of changes cannot even occur anymore, because you never directly access the File.

This has one giant caviat in that all the new things in MediaStore that make that possible do not exist in older versions of Android. So I do currently believe that you will need to implement everything twice, sadly. At least if you want to actively influences where your music is saved to that is.

Those two MediaStore columns are new in Q and do not exist before Q, witch you’ll probably need to use in Q

  • MediaStore.Audio.Media.RELATIVE_PATH with that you can influence the path where it’s saved. So I put «Music/MyAppName/MyLibraryName» there and that will end up saving «song.mp3» into «Music/MyAppName/MyLibraryName/song.mp3»
  • MediaStore.Audio.Media.IS_PENDING this you should be setting to 1 while the song is still being written and then afterwards you can update it to 0.

I’ve also now started to implement things twice with if checks for Android versions. It’s annoying. I don’t want to do it. But it seems like that’s the only way.

I’m just gonna put a bit of code here on how I managed inserting music on Android.Q and below. It’s not perfect. I have to specify the MIME type for Q, because flacs would now become .flac.mp3 somehow, because it does not quite seem to get that.

So, anyways this is a part that I have updated already to work with Q and before, it downloads a Music file from a music player on my NAS. The app is written in kotlin, not sure if that’s a problem for you.

And the MediaStoreHelper Method being this here

One thing when you do not specify the MIME type it seems to assume mp3 is the MIME type. So .flac files would get saved as name.flac.mp3, because it adds the mp3 file type if there is none and it thinks it’s a mp3. It does not add another .mp3 for mp3 files. I don’t currently have the MIME type anywhere. so I’m gonna go ahead and do this now, I guess.

There is also a helpful google IO talk about scoped/shared storage https://youtu.be/3EtBw5s9iRY

Читайте также:  Как взломать traffic rider android

That probably won’t answer all of your questions. It sure enough didn’t for me. But it was a helpful start to have a rough idea what they even did change to begin with.

For deleting and updating files its kinda the same on Q if you call delete on a mediastore entry, the file will be deleted. Before, Q you have to manually delete the file also. But if you do that on Q your app will crash. So again you have to check wether or not youre on Q or an older version of android and take appropriate actions.

Источник

Android Как использовать MediaScannerConnection scanFile

Im добавление изображений в папку на SD-карте. Поскольку изображения и моя папка не сразу видны в галерее im попытка получить MediaScannerConnection для обновления и отображения папка / изображения в галерее. Это не работает так хорошо для меня, так как ничего не появляется в галерее. Im только тестирование в Eclipse AVD.

Я не вижу много разговоров об этом, возможно, потому, что scanFile является новым с api8. Может кто-нибудь показать, как это делается?

Im пытается это в обоих услуги и деятельность, но постоянно uri=null при onScanCompleted.

9 ответов

я понял, что, возможно, вы ищете решение, которое будет работать до уровня api 8, и я не мог понять ответ Митча. Я решил это, создав класс для сканирования одного файла:

и вы бы использовали его так, чтобы сделать MediaScannerConnection сканирование одного файла:

Я искал то же самое, и я нашел это в ApiDemos, ExternalStorage. Решил все мои проблемы, как он сканирует один файл.

или вы можете использовать следующий метод:

проверка файла вызова как:

Не выполняйте sendBroadcast, если вы хотите, чтобы в галерее отображалось только одно изображение. Это было бы огромной тратой ресурсов. Вам нужно будет сделать MediaScannerConnectionClient, а затем вызвать connect() на MediaScannerConnection, который вы делаете из него, чтобы сканировать файл. Вот пример:

пусть ваша деятельность реализует «MediaScannerConnectionClient» и добавьте это к своей деятельности:

Источник

Adding Files to Android’s Media Library Using the MediaScanner

When you add files to Android’s filesystem these files are not picked up by the MedaScanner automatically. But often they should be.

As far as I can tell from a cursory search through Android’s codebase, Android runs a full media scan only on reboot and when (re)mounting the sd card. This might sound bad at first — but think about it. A full scan is taking quite some time and you do not want this to happen arbitrarily, maybe even while the user is using his device heavily.

This means, any file, that must be available in the media library instantaneously, has to be added by you. You have the responsibility to get this right. Even more so, as new devices might support MTP, which means that all files — not only media files — have to made known. Read more about this in the section «Not only relevant for media files».

If you want your files to be added to the media library, you can do so either by using the MediaStore content provider, or by using the MediaScanner. In this post I deal with the MediaScanner only. In a later post I will cover how to use the MediaStore provider for making your files known.

Adding the files using a broadcast

The simplest way to do so is by sending a broadcast:

This works perfectly well and you should be fine with this solution most of the time.

But if you want to be more in control of what is happening, you could use one of the following two methods.

Using the static scanFile() method

If you simply need to know when the files have been added, you could use MediaScannerConnection’s static method scanFile() together with a MediaScannerConnection.OnScanCompletedListener.

Читайте также:  What is an activity in android java

The static method scanFile() is badly named, as it actually takes an array of paths and thus can be used to add multiple files at once and not just one — but it nevertheless does what we want 🙂

Here’s how to use this method:

Parameters for the static scanFile() method
Parameter Use
context The application context
paths A String array containing the paths of the files you want to add
mimeTypes A String array containing the mime types of the files
callback A MediaScannerConnection.OnScanCompletedListener to be notified when the scan is completed

The OnScanCompletedListener itself must implement the onScanCompleted() method. This method gets the filename and the URI for the MediaStore.Files provider passed in as parameters.

Creating an instance of MediaScannerConnection

This is the most complex way to make your files known. But it gives you even more control. You need to implement the MediaScannerConnection.MediaScannerConnectionClient for callbacks.

Your MediaScannerConnectionClient’s implementation is not only called whenever a scan has been completed, but also as soon as the connection has been established. Since this might take a little while, as described in the next section, you might be interested in this callback. The way the API is constructed, you actually need to use this callback method to start the scan.

The following snippet shows you a sample implementation of the MediaScannerConnectionClient interface.

In this implementation I create the MediaScannerConnection within the constructor and here I also call its connect() method.

Note also that I start the scan within the onMediaScannerConnected() callback method.

This way the usage of this interface is as simple as it can get:

Establishing a connection might take a while

Be aware that the connection is not established right away. That’s why the following snippet would cause trouble (that’s the first time I noticed problematic code in Mark Murphy’s otherwise highly recommended book):

This snippet would fail with an IllegalStateException :

java.lang.IllegalStateException: not connected to MediaScannerService

When doing some tests it took on my Optimus One (with an sd card) and on my Galaxy Nexus (with an extra partition) about 20 to 40 milliseconds to establish the connection — on my Archos tablet (also extra partition) about 100 milliseconds.

The scan itself takes even longer — which took me by surprise. On my Archos and Optimus One about 200 milliseconds — on my Nexus even up to 900 (!) milliseconds on its worst run.

Not only relevant for media files

With devices that use MTP instead of the traditional USB storage protocol, the MediaScanner is also used to make arbitrary files accessible via MTP. Thus any files and folders that you do not add to the MediaScanner are invisible between full scans if you plug in your device to your computer!

With the introduction of Honeycomb Google has started to push for MTP. Even if not all handset makers follow Google’s decision, some might — and Google’s own Nexus line definitely does so.

This means that you should use the MediaScanner also for any files that the user might want to download to his computer. It could be anything, e.g. CSV backup files, PDF files and so on. If the user might want to use them on a traditional computer, you have to make these files known using the methods described above.

Wolfram Rittmeyer lives in Germany and has been developing with Java for many years.

He has been interested in Android for quite a while and has been blogging about all kind of topics around Android.

Источник

Оцените статью