belafarinrod91
belafarinrod91

Reputation: 323

Android WebView from Service (without Activity)

I try to get a WebView running from a Service Notification. The WebView is working fine, but I do not get the alerts and some JavaScript functions running.

This is how I create the WebView (nothing special) :

mWebView = new WebView(mServiceContext);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        webSettings.setBuiltInZoomControls(true);

        mWebView.requestFocusFromTouch();

        mWebView.setWebViewClient(new WebViewClient());
        mWebView.setWebChromeClient(new WebChromeClient());    


        mWebView.setOnClickListener(new OverlayOnClickListener());
        mWebView.setOnTouchListener(new OverlayOnTouchListener());
        mWebView.loadUrl("file:///android_asset/www/test/test.html");

And this is the test.html file :

<!DOCTYPE html>
<html>
<head>
    <script>
    function myFunction()
    {
        alert("Hello! I am an alert box!");

        console.log("clicked");
    }
    </script>
</head>
<body>

<input type="button" onclick="myFunction()" value="Show alert box" />
</body>
</html>

When I click the button on the WebView, I get the following log message from JSDialogHelper :

"Cannot create a dialog, the WebView context is not an Activity"

Is there any chance to fix this ?

Upvotes: 2

Views: 3626

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007296

Is there any chance to fix this ?

Implement a real WebChromeClient, one that overrides onJsAlert(). Your setWebViewClient(), setWebChromeClient(), setOnClickListener(), and setOnTouchListener() are useless, and I suspect that setBuiltInZoomControls() and requestFocusFromTouch() are not doing you any good either.

Upvotes: 1

Related Questions