如何启动浏览器打开本地文件

时间:2011-08-10 10:37:20

标签: android

我正在尝试向浏览器发送意图以打开本地文件。我希望使用默认浏览器打开此文件。

if(file.exists()){
  Log.d(TAG, "file.exists");
  Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
  context.startActivity(intent);
}

但是它抛出了我和exeption

08-10 13:27:58.993: ERROR/AndroidRuntime(28453): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=file:///sdcard/release_notes.htm }

如果我使用以下意图浏览器按预期打开google.com

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://google.com"));

此外,当我将文件URL (file:///sdcard/release_notes.htm)写入浏览器地址栏时,它会按预期打开它。

7 个答案:

答案 0 :(得分:9)

仅针对HTML和其他兼容文件启动浏览器。这应该有效:

Intent intent = new Intent(ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "text/html");

答案 1 :(得分:6)

这对我有用。我直接从Android默认浏览器的Manifest.xml获取了mime类型。显然text / html mime仅适用于http(s)和内联方案。

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setDataAndType(Uri.fromFile(filePath), "application/x-webarchive-xml");
startActivity(intent);

不确定它是否适用于所有Android /手机/浏览器组合,但这是我能让它工作的唯一方法。

编辑:使用chrome测试但无效。也不适用于我的2.3.3设备。似乎可以使用Android 4.0中的默认浏览器。

答案 2 :(得分:4)

您需要在意图中添加可浏览类别。

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
intent.addCategory(Intent.CATEGORY_BROWSABLE);
startActivity(intent);

答案 3 :(得分:2)

这是一种更为强大的方法:

private void openInBrowser(File file) {
    final Uri uri = Uri.fromFile(file);
    try {
        final Intent browserIntent = new Intent(Intent.ACTION_VIEW);
        browserIntent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
        browserIntent.setData(uri);
        startActivity(browserIntent);
    } catch (ActivityNotFoundException e) {
        final Intent browserIntent = new Intent(Intent.ACTION_VIEW);
        browserIntent.setDataAndType(Uri.fromFile(file), "text/html");
        startActivity(browserIntent);
    }
}

我在Nexus One(API 16,4.1.2)上进行了测试,其中try正常工作,而Nexus 5(API 22,5.1.1)只有{{1}工作。

答案 4 :(得分:1)

也许这有效:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "text/html");
startActivity(intent);

答案 5 :(得分:0)

问题是新活动无法访问您应用内的html页面,因为它是一个不同的应用,并且没有权限这样做。

答案 6 :(得分:0)

此代码适用于API 10和API 11。

File f = new File("/mnt/sdcard/index.html");

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setDataAndType(Uri.fromFile(f), "application/x-webarchive-xml");
// Have to add this one in order to work on Target 2.3.3 (API 10)
intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
startActivity(intent);
相关问题