How to launch browser to open local file

前端 未结 7 1269
孤街浪徒
孤街浪徒 2020-12-10 05:20

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\");         


        
相关标签:
7条回答
  • 2020-12-10 05:52

    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);
    
    0 讨论(0)
  • 2020-12-10 05:53

    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.

    0 讨论(0)
  • 2020-12-10 05:59

    Maybe this works:

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(file), "text/html");
    startActivity(intent);
    
    0 讨论(0)
  • 2020-12-10 06:02

    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.

    0 讨论(0)
  • 2020-12-10 06:07

    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");
    
    0 讨论(0)
  • 2020-12-10 06:11

    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.

    0 讨论(0)
提交回复
热议问题