Trouble loading local html file into default device browser in Android app

时间:2018-09-18 20:31:33

标签: android android-intent

I am an iOS developer assigned a task in Android, so bear with me, I'm a bit green in Android.

I am attempting to load a local html file that is stored in the device download directory in a folder called user_guide. I want the html file to load in the device's browser (not in a webview for reasons outside the scope of this post). I am using the following code to launch the browser:

String downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
String path = "file://" + downloadPath + "/user_guide/index.html"; // + R.raw.test;
Uri pathUrl = Uri.parse(path);
Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
browserIntent.setData(pathUrl);
context.startActivity(browserIntent);

I obtained the value of path by setting a breakpoint and manually set it in Chrome on my device to verify that is does work and loads the proper file. However, when I try to run this code in the app, I get the following toast message:

Cannot display PDF (index.html is of invalid format)

I'm confused about this message since I am trying to load an html file, not a PDF. Can anyone help me out? THanks!

1 个答案:

答案 0 :(得分:3)

尝试将“ browserIntent.setData(pathUrl)”更改为

browserIntent.setDataAndType(pathUrl, "text/html")

明确指定它是HTML。

我在https://stackoverflow.com/a/7009685/10300291找到了这个建议。