Android在SDCard上查找文件 [英] Android finding files on the SDCard

查看:181
本文介绍了Android在SDCard上查找文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个MP3应用程序,在该应用程序中我希望为SDCard上的文件建立索引.最好的方法是什么?

我的想法.首次启动应用程序时搜索文件,并为SDCard状态更改意图注册广播接收器,并在广播意图时搜索文件.

但是在这种情况下,如果我的广播接收器在10秒钟内未返回,则ANR将出现.

寻找更好和失效保护的想法.谢谢.

解决方案

与Chris同意,MediaScanner会为您找到音乐,并填充MediaStore数据库.这是一些用于查找音乐条目的代码:

        final Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        final String[] cursor_cols = {
                MediaStore.Audio.Media._ID,
                MediaStore.Audio.Media.ARTIST,
                MediaStore.Audio.Media.ALBUM,
                MediaStore.Audio.Media.TITLE,
        };
        final String where = MediaStore.Audio.Media.IS_MUSIC + "=1";
        final Cursor cursor = getContentResolver().query(uri, cursor_cols, where, null, null);
        cursor.moveToNext();
        final String artist = cursor.getString(_cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
        final String album = cursor.getString(_cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
        final String track = cursor.getString(_cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
        doSomethingInteresting(artist, album, track);

数据"字段包含可与MediaPlayer一起使用的句柄.

I'm working on a MP3 application in which I'd like to index the files on my SDCard. What is the best way to do it?

My Idea. Search for files when the application is started for the first time and register a broadcast receiver for the SDCard state change intents and search for the files whenever the intent is broadcasted.

But in this case the ANR would show up if my broadcast receiver doesn't return within 10 seconds.

Looking for better and failsafe ideas. Thanks.

解决方案

Agree with Chris, MediaScanner finds music for you, populating the MediaStore database. Here's some code to look up a music entry:

        final Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        final String[] cursor_cols = {
                MediaStore.Audio.Media._ID,
                MediaStore.Audio.Media.ARTIST,
                MediaStore.Audio.Media.ALBUM,
                MediaStore.Audio.Media.TITLE,
        };
        final String where = MediaStore.Audio.Media.IS_MUSIC + "=1";
        final Cursor cursor = getContentResolver().query(uri, cursor_cols, where, null, null);
        cursor.moveToNext();
        final String artist = cursor.getString(_cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
        final String album = cursor.getString(_cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
        final String track = cursor.getString(_cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
        doSomethingInteresting(artist, album, track);

The "data" field contains a handle you can use with MediaPlayer.

这篇关于Android在SDCard上查找文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆