Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
682 views
in Technique[技术] by (71.8m points)

android - how open local html page in browser

I am making an application in which i want to open a local html page in the browser. I am able to open google.com. But when i'm opening local html file. But i am getting following error

The Request file was not found.

Following is my code:

try
    {
        Intent i = new Intent(Intent.ACTION_VIEW);
        File f=new File("file:///android_asset/www/trialhtml.html");
        Uri uri = Uri.fromFile(f);
        i.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
        i.setData(uri);
        startActivity(i);
    }
    catch(Exception e)
    {
      System.out.print(e.toString());   

    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

file:///android_asset/www/trialhtml.html means nothing to an external application like the Web Browser. Any files in your assets are not accessible by other applications. You have 2 options.

  1. Copy the html file to shared storage so that the the file can be accessed by the webbrowser.
  2. Implement a WebView within a new Activity or fragment in your application then webview.loadUrl("file:///android_asset/www/trialhtml.html");

You do not need to read the asset like other answers are instructing you. WebView will handle this all behind the scenes, including loading other assets like images

As a side note, if the web browser was able to read your files, you would not want to use

        i.setClassName("com.android.browser", "com.android.browser.BrowserActivity");

This is because you are explicitly asking for a certain browser, which may or may not be installed on the user's device. I'm reasonably sure this isn't the case on some modern Android devices that come with only Chrome installed. The correct usage would be something like

Uri uri = Uri.parse("http://www.example.com"); 
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

By not explicitly setting the class and package name, this ensures that no matter which web browser is installed, the users default will be picked.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...