将数组从JS传递到Android

4

你好,我有以下这段活动代码:

public class WebActivity extends ActionBarActivity {

    TextView number;

    WebView mWebView;
    CountDownTimer mTimer;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);


        number = (TextView) findViewById(R.id.number);
        mTimer=new CountDownTimer(10000, 1000) {
            String[] myArray={"javascript:document.getElementById(\"utente\").value=\""+LoginActivity.username+"\"; document.getElementById(\"j_password\").value=\""+LoginActivity.password+"\"; document.querySelector(\"input[type=submit]\").click();","javascript:document.getElementById(\"menu-servizialunno:_idJsp14\").click();"};


            int currentIndex=0;
            public void onTick(long millisUntilFinished) {

                number.setText("seconds remaining: " + millisUntilFinished / 1000 + " " + (currentIndex + 1) + "/" + (myArray.length + 1));
            }
            //code comment start
            // i think this part could be written better
            // but it works!!
            public void onFinish() {
                if (currentIndex<myArray.length) {
                    number.setText("done!");
                    mWebView.loadUrl(myArray[currentIndex]);
                    currentIndex++;
                    mTimer.start();
                } else{
                    mTimer.cancel();

                }

            }
            //code comment end
        };

        mTimer.start();
        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new WebSliderWebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(mWebView, url);
                Toast.makeText(getApplicationContext(), "Done!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(getApplicationContext(), "Oh no! " + description, Toast.LENGTH_SHORT).show();

            }
        });
        mWebView.loadUrl("http://www.ss16374.scuolanext.info");



    }

以及这个JavaScript函数:

function voti( showSubject, showData, showVote ){
    var votitotali = []
    document.getElementById("menu-servizialunno:_idJsp14").click();
    setTimeout(function(){
        elems = document.querySelectorAll("td, legend");
        for(var i = 0; i < elems.length; i++){
            curText = elems[i].innerHTML;
            if( elems[i].tagName == "LEGEND" && showSubject ){
                votitotali += [curText]
                //console.log( curText );
            }else if( elems[i].innerHTML.indexOf("Voto") != -1 && showVote ){
                votitotali += [curText.replace(/.*\(([0-9\.]+)\)/,"$1")]
                //console.log( curText.replace(/.*\(([0-9\.]+)\)/,"$1") );
            }else if( /\d{2}\/\d{2}\/\d{4}/.test(elems[i].innerHTML) && showData ){
                votitotali += [curText.replace(/.*(\d{2}\/\d{2}\/\d{4}).*/,"$1")]
                //console.log( curText.replace(/.*(\d{2}\/\d{2}\/\d{4}).*/,"$1") );
            }
        }
        document.getElementsByClassName("btl-modal-closeButton")[0].click()
    },3000);
    return votitotali
}

我能把votitotali数组存储在我的安卓应用中吗?因为我需要从网站获取一些信息并将它们打印到应用程序的textView上,但我真的不知道如何使用webview做到这一点...


但是...我不能使用那个,因为我需要在webview中实现该函数,该函数必须使用Android webview获取信息。 - Alessio Ragno
1个回答

5
那其实很简单。您需要注入一个具有接收数组的方法的Java对象:
class MyReceiver {
    @JavascriptInterface
    public void receive(String[] input) {
        // input is your data!
    }
}

// At the very beginning
mWebView.addJavascriptInterface(new MyReceiver(), "receiver");
// ...

那么,如果您在JavaScript代码中像这样调用它:
receiver.receive(voti( ... ));

你将在 MyReceiver.receive 方法内获取数组。

请注意,非字符串数组元素(如数字)不会被转换为字符串,并将被替换为 null


这是我所做的,我在mTimer中调用了javascript函数... http://alessio.ragno.info/android.txt - Alessio Ragno
mWebView.loadUrl("receiver.receive(voti(1,1,1));"); 应该改为 mWebView.loadUrl("javascript:receiver.receive(voti(1,1,1));"); - Mikhail Naganov
请注意,注入方法的代码运行在不同的线程上(参见 WebView.html.addJavascriptInterface docs),因此如果您打算将其作为全局变量使用,则需要使用同步。此外,查看此问题以了解可能的跨活动共享数据方式:https://dev59.com/pHI-5IYBdhLWcg3wQV8Z - Mikhail Naganov
我编辑了接收函数并添加了另外两个数组... 这些很大...
然后我得到了这个错误:JNI ERROR (app bug): local reference table overflow (max=512)。 我该怎么修复它?
- Alessio Ragno
可能需要减少传递的信息量。看起来在将数据从JS转换为Java时,创建的临时Java对象数量超过了Java虚拟机的能力。 - Mikhail Naganov
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接