如何使用已安装的应用程序打开文件?

时间:2015-03-21 04:34:24

标签: android android-intent

我想在Android中使用已安装的应用打开指定文件。我怎样才能做到这一点?

我使用的是Google提供的以下代码,但它始终返回"No app to open this file"。但是,如果我在其他文件管理器中打开该文件,我会看到打开该文件的不同选项。代码:

public void open(View v) {
        String name = ((TextView) v).getText().toString();
        File f = new File(path + name);
        if (f.isDirectory()) {
            showFiles(f);
        } else if (f.isFile()) {
            Intent openFileIntent = new Intent(Intent.ACTION_VIEW);
            openFileIntent.setData(Uri.fromFile(f));
            if (openFileIntent.resolveActivity(getPackageManager()) != null) {
                startActivity(openFileIntent);
            } else {
                Toast.makeText(this, "No app to open this file.",
                        Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "Selected item is not a file.",
                    Toast.LENGTH_SHORT).show();
        }
    }

1 个答案:

答案 0 :(得分:1)

您应指定MIME类型,以便Android知道哪个应用能够打开/查看该文件。这应该适合你:

public void open(View v) {
    String name = ((TextView) v).getText().toString();
    File f = new File(path + name);
    if (f.isDirectory()) {
        showFiles(f);
    } else if (f.isFile()) {
        Intent openFileIntent = new Intent(Intent.ACTION_VIEW);
        openFileIntent.setDataAndType(Uri.fromFile(f), getMimeTypeFromFile(f));
        if (openFileIntent.resolveActivity(getPackageManager()) != null) {
            startActivity(openFileIntent);
        } else {
            Toast.makeText(this, "No app to open this file.",
                    Toast.LENGTH_SHORT).show();
        }
    } else {
        Toast.makeText(this, "Selected item is not a file.",
                Toast.LENGTH_SHORT).show();
    }
}

private String getMimeTypeFromFile(File f){
    Uri fileUri = Uri.fromFile(f);
    String fileExtension
            = MimeTypeMap.getFileExtensionFromUrl(fileUri.toString());
    String fileType 
            = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
    if (fileType == null) 
        fileType = "*/*";
    return fileType;
}