Tom N Tech
Tom N Tech

Reputation: 270

Android, launching intent through webview

I am trying to implement something where I have a simple native application containing a webview and a website I have written hosted on the net.

The idea is that my Android app loads (and later iOS will be supported as well), the website I am making it loaded into the webview. However, there is a single element on one of the webpages, id="LaunchNativeApp", that when onClick is received, I want to launch an intent to the barcode scanner from my native application. How do I go about doing this?

A use case for this is:

  1. User launches native android app

  2. Native android app loads www.mywebsiteaddress.co.uk

  3. User navigates www.mywebsiteaddress.co.uk and goes into the page www.mywebsiteaddress.co.uk/inputDetails

  4. User clicks in the text input field

  5. Native android app loads camera

  6. User reads barcode

  7. Barcode inserted into text input field

  8. List item

Steps 1 to 3 I can do, 4 through 8 I require some advice on, any ideas if this is even possible?

Many Thanks

Upvotes: 0

Views: 1227

Answers (2)

P5music
P5music

Reputation: 3337

You can also use addJavascriptInterface(Object, String) so you can call methods of a java object from javascript. You do not need to put scripts in the page server-side, it is enough to inject some javascript by calling mWebView.loadUrl("javascript: {your javascript code here} "); if you know the HTML elements in the page.

Upvotes: 2

CSmith
CSmith

Reputation: 13458

On your web page, you can implement javascript code similar to at Step 4:

window.location = 'myApp://message?param=X&param2=Y';

Then in your WebView, you'd have a WebViewClient shouldOverrideUrlLoading implementation:

mWebView.setWebViewClient(new WebViewClient() 
{

    public boolean shouldOverrideUrlLoading(WebView view, String url)
    {


        // handle myApp links
        if (url.startsWith("myApp"))
        {
            try
            {
                java.net.URI uri = new java.net.URI(url);

                // MESSAGE
                if (uri.getHost().equalsIgnoreCase("message"))
                {
                          // do something here...(e.g. load Camera activity)
                }

            }
            catch (Exception e)
            {
            }

            return (true);
        }

        return (false);
    }

});

You'd 'trap' the javascript calls in your native code and respond to them (e.g. load a camera activity, etc).

You could then return results back to your WebView by calling back into the page DOM

String str = String.format("javascript:{your javascript code here}");
mWebView.loadUrl(str);

Upvotes: 0

Related Questions