我在webview中使用带有JavascriptInterface功能的WebView。这是完整的工作示例:
package com.example.apps;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
private WebSettings webSettings;
public class myJsInterface {
private Context con;
public myJsInterface(Context con) {
this.con = con;
}
@android.webkit.JavascriptInterface
public void showToast(final String msg) {
// Show small piece of text at the bottom of screen
runOnUiThread(new Runnable() {
public void run() {
CharSequence text = msg;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(con, text, duration);
toast.show();
}
});
}
@android.webkit.JavascriptInterface
public void showToast2(final String msg, final Callable<Integer> myCallback) {
// Show small piece of text at the bottom of screen
runOnUiThread(new Runnable() {
public void run() {
if (myCallback == null) {
Toast.makeText(con, "cb is null", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(con, msg, Toast.LENGTH_LONG).show();
}
}
});
}
}
private myJsInterface mjsi = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView)findViewById(R.id.webView);
webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mjsi = new myJsInterface(this);
mWebView.addJavascriptInterface(mjsi, "MyInterface");
mWebView.loadUrl("file:///android_asset/index.html");
}
@Override
public void onBackPressed() {
mWebView.loadUrl("file:///android_asset/index.html");
}
}
在javascript中我可以调用MyInterface.showToast(&#34; hello&#34;)并且它可以工作。它也适用于int等。但是如何将第二个参数作为javascript函数(回调)传递?我想打电话(来自javascript):
MyInterface.showToast("hello", function () { console.log('something'); });
我试过了:
public void showToast(final String msg, final String callback)
public void showToast(final String msg, final Object callback)
public void showToast(final String msg, final JsResult callback)
但是两者都返回undefined或null作为第二个参数。 示例index.html文件位于:
<html>
<head>
<meta name="viewport" content="width=device-width" />
</head>
<body>
This is index.html<br>
<textarea id="code">MyInterface.showToast("foo");</textarea><br>
<textarea id="out">out</textarea><br>
<button onclick="try { out.value = eval(code.value); } catch (e) { out.value = e; }">eval</button>
<button onclick="out.value = ''; code.value = '';>clear</button>
</body>
</html>
答案 0 :(得分:-1)
难以使用您的代码,但如果您可以向我们展示更多代码,我会编辑我的答案。这就是你如何处理Java接口中的回调类型
public interface Callback<T> {
public void callback(T t);
}
Callable
import java.util.concurrent.Callable;
interface MyInterface{
public void showToast(final String msg, Callable<Integer> myCallback);
}
myCallback.call();
显然,最后一行将在你的函数的实现中进行,如果你有任何参数,那么只需将它们传递给调用。