Android 如何使用字符串在mediastore光标中实际搜索歌曲

Android 如何使用字符串在mediastore光标中实际搜索歌曲,android,Android,我已经设置了光标,但我仍在努力实际搜索它。如何搜索曲目名称?如何获取其ID以便将其传递给mediaplayer?我尝试过不同的事情,但没有成功 基本上,我想知道如何在mediastore中搜索特定字符串(本例中为string songToPlay),获得结果,获得最佳匹配的ID,并将其传递给我的mediaplayer服务,以便在后台播放。但我唯一要问的是如何获得身份证 这是我正在使用的代码: Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_UR

我已经设置了光标,但我仍在努力实际搜索它。如何搜索曲目名称?如何获取其ID以便将其传递给mediaplayer?我尝试过不同的事情,但没有成功

基本上,我想知道如何在mediastore中搜索特定字符串(本例中为string songToPlay),获得结果,获得最佳匹配的ID,并将其传递给我的mediaplayer服务,以便在后台播放。但我唯一要问的是如何获得身份证

这是我正在使用的代码:

Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] songToPlay = value.split("play song");
    String[] searchWords = songToPlay[1].split(" ");
                String [] keywords = null;
                StringBuilder where = new StringBuilder();
                where.append(MediaStore.Audio.Media.TITLE + " != ''");
    String selection = where.toString();
                    String[] projection = {
                            BaseColumns._ID,   
                            MediaStore.Audio.Media.MIME_TYPE, 
                            MediaStore.Audio.Artists.ARTIST,
                            MediaStore.Audio.Albums.ALBUM,
                            MediaStore.Audio.Media.TITLE
                    };
for (int i = 0; i < searchWords.length; i++) {
                        keywords[i] = '%' + MediaStore.Audio.keyFor(searchWords[i]) + '%';
                    }

                Cursor cursor = this.managedQuery(uri, projection, selection, keywords, MediaStore.Audio.Media.TITLE);              
                if (cursor.moveToFirst()) {
                    do{
                        test.setText(cursor.getString(cursor
                                .getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
                    }while(cursor.moveToNext());
                }

这将在
MediaStore
中搜索标题等于
songToPlay
字符串值的所有歌曲

Cursor cursor = getContentResolver().query(
    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 
    null, 
    MediaStore.Audio.Media.TITLE + "=?", 
    new String[]{songToPlay}, 
    MediaStore.Audio.Media.TITLE + " ASC");
当然,您可以查询光标以获取任何结果的ID(和任何其他列)

while (cursor.moveToNext()) {
    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
    long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
    // Whatever else you need
}

但是,这需要精确匹配,您可能希望使用
like
操作符进行更模糊的匹配。

如果我要求的太多,我很抱歉,但我真的被卡住了。我真的还是不知道数据库查询。声明游标后,如何从游标获取文件位置或音乐ID?我几乎很沮丧——我已经两天多没能在这方面取得进展了。我已经把我当前的代码放在了原来的帖子里。嗨,肯,这是一个非常有用的答案,谢谢你发布它。我只是想知道你能否详细说明一下like运算符?我有这个代码来工作,但正如你所说,它需要确切的歌曲名称,我如何才能使它,当我搜索时,它将填充包含我正在搜索的字符的歌曲?非常感谢。我还提出了另一个问题:
while (cursor.moveToNext()) {
    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
    long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
    // Whatever else you need
}