How to launch browser to open local file

前端 未结 7 1271
孤街浪徒
孤街浪徒 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: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.

提交回复
热议问题