【问题标题】:Intent.CATEGORY_APP_MUSIC with Intent.setDataAndType returns no result带有 Intent.setDataAndType 的 Intent.CATEGORY_APP_MUSIC 不返回任何结果
【发布时间】:2018-10-21 06:16:34
【问题描述】:

我有一个音频文件,我希望设备默认应用或任何其他可以处理音频文件的已安装应用播放此音频。所以我有这个:

private void playMedia(String mediaPath) {
    try {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_APP_MUSIC);
        String extension = FilenameUtils.getExtension(mediaPath);
        String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        intent.setDataAndType(Uri.parse(mediaPath), mimetype);
        startActivity(intent);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

如果我不设置setDataAndType,我的两个玩家会回复,

但是如果我设置setDataAndType:

ActivityNotFoundException: 找不到处理 Intent 的 Activity { act=android.intent.action.MAIN cat=[android.intent.category.APP_MUSIC] dat=/storage/emulated/0/Audio.mp3 typ=audio/mpeg

我正在使用的设备(API 24)有几个播放器,例如mxPlayer,playerPro,shareIt Music,google play music,default player ...

我在这里做错了吗?

更新(最终答案)

正如接受的答案所建议的那样,我尝试使用文件,所以工作代码是:

private void playMedia() {
    try {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String extension = FilenameUtils.getExtension(inPath);
        String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        String type = null;
        try {
            type = mimetype.split("/")[0].toLowerCase().trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (type==null)
            type="*";
        File file = new File(inPath);
        intent.setDataAndType(Uri.fromFile(file), type+"/*");
        startActivity(Intent.createChooser(intent, FilenameUtils.getBaseName(inPath)));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

【问题讨论】:

    标签: android android-intent


    【解决方案1】:

    你可以试试这个:

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_APP_MUSIC);
    String extension = FilenameUtils.getExtension(mediaPath);
    String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    
    File sdcard = Environment.getExternalStorageDirectory();
    File audioFile = new File(sdcard.getPath() + "/Music/goodmorningandroid.mp3"); 
    intent.setDataAndType(Uri.fromFile(audioFile), mimetype); //notice this line
    

    已编辑: 需要读写 sdcard 的权限。

    【讨论】:

    • 谢谢你的回复,我用文件试过了,还是一样的异常。
    • 但是,我尝试使用 ACTION_VIEW 意图的 fromFile,而不是 CATEGORY_APP_MUSIC。我得到了我想要的结果,再次感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 2017-12-28
    • 2017-12-09
    • 2020-10-03
    • 2017-03-19
    • 2017-05-20
    • 2012-08-08
    相关资源
    最近更新 更多