Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

android - Access local file in a WebView

My native app includes a WebView, and the WebView loads a web page off web. For example, the html is loaded from

http://dongshengcn.com/test.html

It seems any page loaded from web (instead of local) can not load any file from local device.

My question is:

Is it possible for a http://dongsheng.com/test.html loaded to a webview (as part of native app) to access file on local device?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Here are a couple of things to try:

  1. To use local files you need to place them in your project's assets folder and invoke them using URLs such as file:///android_asset/. For example, if you add mypage.html in your assets folder, then you can invoke it in the webview with file:///android_asset/mypage.html.

  2. Check to make sure that you have the appropriate webview permissions in your Manifest. For the webview to work correctly, you need:

    <uses-permission android:name="android.permission.INTERNET" />

  3. Take a look at the following app on Github, which as a bonus also fixes a couple of bugs with the webview in Honeycomb and ICS. It is a full example on how to use the webview with local files: https://github.com/bricolsoftconsulting/WebViewIssue17535FixDemo

EDIT: Addendum after question clarification:

Yes, it is possible to load a local page from the web, but you must use a trick to bypass the browser's security measures.

Replace the file://android_asset/ portion of the URLs with a custom scheme (e.g. file///android_asset/mypage.html becomes myscheme:///mypage.html), and place these custom scheme URLs in your page. Implement WebViewClient's shouldOverrideUrlLoading, check if the URL begins with the custom scheme and if so redirect to the local page using webview.loadUrl.

    mWebView.setWebViewClient(new WebViewClient()  
    {  
        @Override  
        public boolean shouldOverrideUrlLoading(WebView view, String url)  
        {  
            if (url != null && url.startsWith("myscheme://"))  
            {  
                String newUrl = url.replace("myscheme://", "file://android_asset/");  
                mWebView.loadUrl(newUrl);  
                return true;  
            }  
            return false;  
        }  
    }  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...