android - 如何刷新 Android 上的 MediaStore?

标签 android mediastore

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

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

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

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

我着手编写自己的应用程序来刷新或删除 MediaStore 数据库并从头开始,但我并没有取得太大进展。我有一个运行以下代码的 Android 应用程序:

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

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

完整代码:

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

最佳答案

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

添加文件:

每当您添加一个文件时,通知MediaStoreContent Provider使用:

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

删除文件:

同样,当你删除一个文件时,通知MediaStoreContent Provider使用:

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

关于android - 如何刷新 Android 上的 MediaStore?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49957676/

相关文章:

android - 从另一个 Activity 更改一个 Activity 的背景

java - 添加点和平移后 AChartEngine 崩溃

android - 使用适用于 Android 和 IOS 的 Xamarin Forms,如何显示 4 种独特状态的状态指示器

android - 将 Activity 之间的数据从 ListView 传递到另一个 Activity

android - 通过 Android Media Store 将图像存储在新文件夹中

java - 以编程方式创建文件夹时媒体存储不工作

java - ProGuard 中类路径前的感叹号有什么作用?

android - 从Android设备android编程获取所有照片

android - MediaStore.Video.Media.DURATION 中的 DURATION 错误

android - MediaStore.Audio.Artists 中没有 "number_of_albums column"