如何在 Android 上刷新 MediaStore?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3300137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:35:49  来源:igfitidea点击:

How can I refresh MediaStore on Android?

androidmediastore

提问by roryok

This started out as a general user question on Android forums. However it's become, by necessity, a programming question. Here's my problem.

这最初是 Android 论坛上的一般用户问题。然而,它必然成为一个编程问题。这是我的问题。

Android has a service - MediaScanner - which runs in the background any time (I believe) the SD card is un-mounted and re-mounted. This service collects data on all the media files on the card, and provides a SQLite DB which can be queried by music applications. Most music applications use this service as it saves on battery-drain associated with scanning the SD card.

Android 有一项服务 - MediaScanner - 它可以在任何时候(我相信)卸载并重新安装 SD 卡时在后台运行。该服务收集卡上所有媒体文件的数据,并提供可被音乐应用程序查询的 SQLite DB。大多数音乐应用程序都使用此服务,因为它可以节省与扫描 SD 卡相关的电池消耗。

Since I started using android, I've consistently had a problem whereby M3U playlists synchronised to the device remain in this SQLite DB even after being deleted from the SD Card. It's gotten to the point where I now have a collection of about 40 playlists showing up in any music app I use, despite there only being around 10 m3u files on the card. The remaining playlists do not play, and are empty. I can remove them manually by deleting them from the music app, but I'm sick of doing this. There has to be a better way to remove these ghost playlists.

自从我开始使用 android 以来,我一直遇到一个问题,即同步到设备的 M3U 播放列表即使在从 SD 卡中删除后仍保留在此 SQLite 数据库中。尽管卡上只有大约 10 个 m3u 文件,但我现在在我使用的任何音乐应用程序中都显示了大约 40 个播放列表的集合。其余的播放列表不播放,并且是空的。我可以通过从音乐应用程序中删除它们来手动删除它们,但我厌倦了这样做。必须有更好的方法来删除这些幽灵播放列表。

There are two apps on the Android Market - SDRescan and Music Scanner, which supposedly do exactly this but neither of them work.

Android Market 上有两个应用程序 - SDRescan 和 Music Sc​​anner,据说它们完全可以做到这一点,但它们都不起作用。

I set about writing my own app to refresh or delete the MediaStore database and start from scratch, but I'm not getting very far. I've got an android app which runs the following code :

我开始编写我自己的应用程序来刷新或删除 MediaStore 数据库并从头开始,但我并没有走多远。我有一个运行以下代码的android应用程序:

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, 
        Uri.parse("file://" + Environment.getExternalStorageDirectory()))); 

I've found a few examples of this code online as a way to scan the SD Card but I'm not having any luck with it whatsoever. Any tips?

我在网上找到了一些此代码的示例,作为扫描 SD 卡的一种方式,但我对此没有任何运气。有小费吗?

FULL CODE:

完整代码:

package com.roryok.MediaRescan;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;

public class MediaRescan extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, 
                Uri.parse("file://" + Environment.getExternalStorageDirectory()))); 
        setContentView(R.layout.main);
    }

    //Rescan the sdcard after copy the file
    private void rescanSdcard() throws Exception{     
      Intent scanIntent = new Intent(Intent.ACTION_MEDIA_MOUNTED, 
                Uri.parse("file://" + Environment.getExternalStorageDirectory()));   
      IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_SCANNER_STARTED);
      intentFilter.addDataScheme("file");     
      sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, 
                Uri.parse("file://" + Environment.getExternalStorageDirectory())));    
    }
}

采纳答案by roryok

Ok, I've done it.

好的,我已经做到了。

Rather than rescan the card, the app iterates through all the playlists in mediastore and checks the length of the _data field. I discovered that for all the lists with no associated M3U file, this field was always empty. Then it was just a case of finding the source code for the original android music app, finding the delete method and using that to delete any playlists with a length of 0. I've renamed the app PlaylistPurge (since it doesn't 'rescan' anymore) and am posting the code below.

该应用程序不会重新扫描卡,而是遍历 mediastore 中的所有播放列表并检查 _data 字段的长度。我发现对于所有没有关联 M3U 文件的列表,这个字段总是空的。然后只是找到原始 android 音乐应用程序的源代码,找到删除方法并使用它来删除任何长度为 0 的播放列表。我已将应用程序重命名为 PlaylistPurge(因为它不会“重新扫描” ' 再)并在下面发布代码。

I'll probably also publish this somewhere, either on the Market or on my own site, http://roryok.com

我可能也会在某个地方发布它,无论是在市场上还是在我自己的网站上,http://roryok.com

package com.roryok.PlaylistPurge;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;

public class PlaylistPurge extends ListActivity {

    private List<String> list = new ArrayList<String>();
    private final String [] STAR= {"*"};

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ListAdapter adapter = createAdapter();
        setListAdapter(adapter);
    }

    /**
     * Creates and returns a list adapter for the current list activity
     * @return
     */
    protected ListAdapter createAdapter()
    {
        // return play-lists
        Uri playlist_uri= MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI;    
        Cursor cursor= managedQuery(playlist_uri, STAR, null,null,null);
        cursor.moveToFirst();
        for(int r= 0; r<cursor.getCount(); r++, cursor.moveToNext()){
            int i = cursor.getInt(0);
            int l = cursor.getString(1).length();
            if(l>0){
                // keep any playlists with a valid data field, and let me know
                list.add("Keeping : " + cursor.getString(2) + " : id(" + i + ")");
            }else{
                // delete any play-lists with a data length of '0'
                Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, i);
                getContentResolver().delete(uri, null, null);
                list.add("Deleted : " + cursor.getString(2) + " : id(" + i + ")");
            }
        }       
        cursor.close();
        // publish list of retained / deleted playlists
        ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);

        return adapter;
    }
}

UPDATE:

更新:

Here's a link to a post on my blog about the app http://roryok.com/blog/index.php/2010/07/23/clearing-out-deleted-playlists-in-android/

这是我博客上有关该应用程序的帖子的链接http://roryok.com/blog/index.php/2010/07/23/clearing-out-deleted-playlists-in-android/

UPDATE 2: Tuesday, April 9, 2013

更新 2:2013 年 4 月 9 日,星期二

I've gotten a lot of traffic to my blog from this post, and a huge number of emails from people thanking me for it. Glad it helped out! Any potential users should know that my crappy app currently crashes as soon as you run it, but actually does what it's supposed to do! I've always intended to go back and fix this crashing behaviour and put it on the market, hopefully 2013 will be the year I do that.

这篇文章为我的博客带来了大量流量,并且收到了大量感谢我的人的电子邮件。很高兴它有所帮助!任何潜在用户都应该知道,我的蹩脚应用程序当前一运行就会崩溃,但实际上做了它应该做的事情!我一直打算回去修复这种崩溃行为并将其投放市场,希望 2013 年将是我这样做的一年。

回答by Pascal

Here is an easy to use 'single file based' solution:

这是一个易于使用的“基于单个文件”的解决方案:

Adding a file:

添加文件:

Whenever you adda file, inform MediaStore's Content Providerusing:

每当您添加文件时,请使用以下命令通知MediaStore内容提供者

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(newMediaFile)));

Deleting a file:

删除文件:

Similarly, when you deletea file, inform MediaStore's Content Providerusing:

同样,当您删除文件时,请使用以下命令通知MediaStore内容提供者

getContentResolver().delete(uri, null, null)  // (Credit goes to [DDSports][1])

回答by Michael

You can request a rescan of specific files using the following code.

您可以使用以下代码请求重新扫描特定文件。

NOTE: The MIME TYPE passed is important. I noticed changes made to MP3 ID3 tags did not refresh properly in the SQLite if I used "*/*", however using "audio/mp3" worked

注意:传递的 MIME TYPE 很重要。我注意到如果我使用“*/*”,对 MP3 ID3 标签所做的更改不会在 SQLite 中正确刷新,但是使用“audio/mp3”有效

MediaScannerConnection.scanFile(
    context, 
    new String[]{ pathToFile1, pathToFile2 }, 
    new String[]{ "audio/mp3", "*/*" }, 
    new MediaScannerConnectionClient()
    {
        public void onMediaScannerConnected()
        {
        }
        public void onScanCompleted(String path, Uri uri)
        {
        }
    });