我正在构建一个 Android 应用程序,其中在 webView 上加载失败的 HTTP 文件,该文件位于 asset 文件夹中。下面是击败HTTP文件的代码。
<html>
<head>
</head>
<body>
<a href="javascript:void(0);" onclick="init();">Click on this link for a log
message</a>
<br><br><br><br><br>
<script>
function init(){
android.log('Data from JS');
android.log(android.data);
}
function showMessage(str){
android.log(str);
}
</script>
</body>
</html>
OnCreate代码
//add interface
wv.addJavascriptInterface(jsInterface, "android");//android is the
keyword that will be exposed in js
OnClick方法和接口(interface)方法
public void click(View view){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
wv.evaluateJavascript("javascript:showMessage('Hello World!')", null);
}
}
//javascript interface
private class JsInterface {
@JavascriptInterface
//function that will be called from assets/test.js
//js example: android.log('my message');
public String data() {
return "DATA FROM ANDROID";
}
public void log(String msg) {
Log.d("MSG FROM JAVASCRIPT", msg);
}
}
上面是我如何在 JavaScript 中使用界面的完整代码。很久以前,我在我的旧项目中使用过同样的方法,但现在它不起作用了,任何人都可以回答我这个方法在android中是否已被弃用,或者还有其他解决方法吗?
最佳答案
这是js接口(interface)类:
public class JS_INTERFACE {
Context mContext;
/** Instantiate the interface and set the context */
JS_INTERFACE(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void native_showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
@JavascriptInterface
public void native_ShowNotifyTest1(String toast , String BigOrSmall ) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
WebSettings settings = webView1.getSettings();
// Enable Javascript
settings.setJavaScriptEnabled(true);
webView1.addJavascriptInterface(new JS_INTERFACE(getContext()), "android");
}
我使用 onCreateView 进行 init 。
更新答案:
在您的应用程序中使用 JQ(简单使用评估Javascript):
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("someJQFunction();", null);
}
else {
webView.loadUrl("javascript: someJQFunction();");
}
关于javascript - 如何在javascript中制作界面并调用android方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45343747/