android studio webview获取数据和onfinish [英] android studio webview get data and onfinish

查看:856
本文介绍了android studio webview获取数据和onfinish的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含webview的android活动,我有一个包含本地变量标记的页面。当用户得到正确答案时,局部变量将增加。在网页中,有一个名为 exit 的按钮,它应该关闭网页并返回到android中的活动,它应该携带本地变量标记也回到活动。我想询问如何在网页中完成退出按钮以关闭页面并使用Javascript返回本地变量,以及android中的活动如何从网页接收本地变量。

I have an android activity that holds the webview and I have a page that contains a local variable marks. The local variable will be increased when user got the correct answer. In the webpage, there is a button called exit which is supposed to close the webpage and go back to the activity in android, and it should carry the local variable marks back to the activity too. I want to ask how the exit button can be done in the webpage to close the page and return local variable by using Javascript and how can the activity in android receive the local variable from the webpage.

我在android中的活动:

My activity in android:

private WebView webview;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //setContentView(R.layout.activity_main);

    webview = new WebView(this);
    webview.getSettings().setJavaScriptEnabled(true);

    try {
        webview.setWebViewClient(new WebViewClient());
        webview.loadUrl("file:///android_asset/index.html");
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
    setContentView(webview);
}

我的退出按钮是div:

My exit button is a div:

<div class="exit" onclick="finish()">Exit</div>

我将使用 finish()函数返回变量并关闭网页回到android中的活动。

I am going to use the finish() function to return the variable and close the webpage back to the activity in android.

function finish() {}


推荐答案

在onCreate中为您的网页浏览注册javascript接口:

Register a javascriptinterface to your webview in onCreate:

this.webview.addJavascriptInterface(new MyJSInterface(this), "Android"); 

在您的活动中实施setCount方法:

Implement setCount method in your Activity:

public void setCount (int count) {
    //do what ever you want with count
}

创建一个新的JavascriptInterface-Class:

Make a new JavascriptInterface-Class:

public class MyJSInterface {
    private YourActivity yourActivity = null;
    public MyJSInterface (YourActivity yourActivity) {
        this.yourActivity = yourActivity;
    }

    @JavascriptInterface
    public void invoke (int count)  {
          this.yourActivity.setCount(count);
    }
}

在javascript中:

And in javascript:

function finish(marks) {
    if (Android !== undefined) {
        if (Android.invoke !== undefined)  {
            Android.invoke(marks);
        }
    }
}

这篇关于android studio webview获取数据和onfinish的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆