通过打开文件启动应用程序

时间:2018-09-18 10:21:41

标签: android android-intent

我创建了一个音乐播放器,现在我想实现一项功能,如果我单击一个文件(例如在Total Commander中),它将在我的应用程序中打开。它已经可以在台式机上运行,​​但是现在我也想在Android中实现此功能。

我知道一定已经被问过了,但是我找不到答案。

我已经发现我需要在AndroidManifest.xml中定义一个意图过滤器:

        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>
            <data android:scheme="file"/>
            <data android:mimeType="audio/*"/>
        </intent-filter>

我做到了,现在,如果我单击一个音乐文件,我的应用程序将打开(或者可以选择它)。但是现在我也需要在Java部分中做一些事情(我相信主要活动onCreate函数)。我该如何处理?

谢谢。

1 个答案:

答案 0 :(得分:1)

您指定的意图过滤器已经朝着正确的方向迈出了一步。 现在,其他(类似于Explorer的)应用程序可以启动您的应用程序。 下一步,您需要在活动onCreate(...)函数中接收数据。可以这样完成:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //setContentView(R.layout.main);

    // Get the intent that started this activity
    Intent intent = getIntent();
    Uri data = intent.getData();

    // Figure out what to do based on the intent type
    if (intent.getType().equals("audio")) {
        // Handle intents with audio ...
        String filePath = data.toString();
        // Do some handling here !
    }
}

首先,您需要捕获其他应用程序使用的Intent,以调用您的应用程序。该意图包含文件(作为URI)结构的路径。然后,您唯一需要做的就是获取URI字符串并从中获取音乐文件的路径。

有关意图过滤的信息可以在这里阅读: https://developer.android.com/training/basics/intents/filters