Mike Baxter
Mike Baxter

Reputation: 7268

Calling activity function from separate class

I have been following the android tutorial (found here), trying to get a simple web application to work.

I have an activity called CalendarActivity which holds a WebView. This WebView renders a page from the assets\www\ folder. I also have a CalendarInterface, which holds the methods called by the javascript from the html page.

What I want to do is to be able to call the finish() function for the activity via javascript. However, since this can only be called from within the activity - how do I achieve this using a separate interface class?

Upvotes: 0

Views: 682

Answers (1)

David Wasser
David Wasser

Reputation: 95618

Using the linked page as an example, you should be able to do something like this:

public class WebAppInterface {
    Activity mActivity;

    /** Instantiate the interface and set the activity */
    WebAppInterface(Activity activity) {
        mActivity = activity;
    }

    /** Finish activity from the web page */
    @JavascriptInterface
    public void finishActivity() {
        mActivity.finish();
    }
}

Now, in your activity you add the JS interface like this:

WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");

And in your webpage, you can finish the activity by clicking a button, like this:

<input type="button" value="Finish the activity now" onClick="finishActivity()" />

<script type="text/javascript">
    function finishActivity() {
        Android.finishActivity();
    }
</script>

Upvotes: 3

Related Questions