【问题标题】:How to open mp3 file on phone's default app?如何在手机的默认应用程序上打开 mp3 文件?
【发布时间】:2021-10-31 13:33:05
【问题描述】:

目前我的代码是这样的:

当用户在我的文件管理器中单击音频文件时,它应该在他们的默认音频应用程序中打开它,但文件管理器应用程序只是崩溃了。 apk 和 pdf 文件也会发生这种情况,但我从代码中删除了这些文件以专注于 mp3 问题。

另外,如果有人知道一种无需指定扩展名即可打开文件的通用方法,那就太棒了!

提前感谢,我的朋友们。

Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_VIEW);
                            if (files[position].toString().contains(".png") || files[position].toString().contains(".jpg") || files[position].toString().contains(".jpeg")) {
                                intent.setDataAndType(Uri.parse(files[position].toString()), "image/jpeg");
                            } else if (files[position].toString().contains(".mp4")) {
                                intent.setDataAndType(Uri.parse(files[position].toString()), "video/*");
                            } else if (files[position].toString().contains(".mp3")) {
                                intent.setDataAndType(Uri.parse(files[position].toString()), "audio/*");
                            } else if (files[position].toString().contains(".doc") || files[position].toString().contains(".docx")) {
                                intent.setDataAndType(Uri.parse(files[position].toString()), "application/msword");
                            } else {
                                intent.setDataAndType(Uri.parse(files[position].toString()), "*/*");
                            }
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);

【问题讨论】:

    标签: java android android-intent


    【解决方案1】:

    你可以像这样使用意图,

    Intent intent = new Intent();  
    intent.setAction(android.content.Intent.ACTION_VIEW);  
    intent.setDataAndType(Uri.fromFile(new File(path)), "audio/*");  
    startActivity(intent);

    【讨论】:

    • 当我尝试打开一个 mp3 文件时,应用程序不断崩溃,即使使用此代码也是如此。
    【解决方案2】:

    我不明白您在代码中做了什么,但是如果您有 mp3 文件的 uri,请使用 intent。

    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
    

    编辑:我检查了我的代码库是否有这样的用途,我打开了一个 txt 文件进行导入。设置类型总是让我的应用程序崩溃,因此我将类型设置为“* /*”。请参阅下面的类似代码。

    public void importDictionary() {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("*/*"); //needed to not make it crash
    startActivityForResult(intent, 2);
    }
    

    之后覆盖 onActivityResult 以执行操作

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2 && resultCode == Activity.RESULT_OK) {
        // your code here
        }
    }
    

    【讨论】:

    • 如果我使用此代码,它会与任何文件一起崩溃。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-21
    相关资源
    最近更新 更多