I\'m trying to send intent to browser to open local file. I wish to use default browser to open this file.
if(file.exists()){
Log.d(TAG, \"file.exists\");
You need to add browsable category in the intent.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
intent.addCategory(Intent.CATEGORY_BROWSABLE);
startActivity(intent);
Here's a slighly more robust approach:
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);
}
}
I've tested this on a Nexus One (API 16, 4.1.2), where the try
works, and a Nexus 5 (API 22, 5.1.1), where only the catch
works.
Maybe this works:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "text/html");
startActivity(intent);
This is what's working for me. I took the mime type directly from the Manifest.xml of the Android's default browser. Apparently the text/html mime is only for http(s) and inline schemes.
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setDataAndType(Uri.fromFile(filePath), "application/x-webarchive-xml");
startActivity(intent);
Not sure if it works in every android/phone/browser combination but it's the only way I could get it to work.
Edit: Tested with chrome and doesn't work. Also doesn't work with my 2.3.3 device. Seems to work with the default browser in Android 4.0.
The browser is started only for HTML and other compatible files. this should work:
Intent intent = new Intent(ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "text/html");
The problem is that the new activity has no access to the html page inside your app since it is a different app and it has no permissions to do so.