Android Studio开发安卓app 安卓与webview中的js交互
1.webview中的页面调用android中的方法
在Android Studio开发安卓app 封装WEB(H5,URL)
的基础上增加该功能
1. APP新增 JsInteration.java
package com.bsoft.myapplication;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.webkit.JavascriptInterface;
/**
*
* author:gaom
* @since: 2022/6/14 9:11
* desc: 安卓与webview html 中的 js交互
*/
public class JsInteration {
TextToSpeech textToSpeech;
public JsInteration(TextToSpeech textToSpeech){
this.textToSpeech=textToSpeech;
}
/**
* java方法 供H5调用
* @return
*/
@JavascriptInterface
public String textToSpeech(String text) {
Log.d("textToSpeech",text);
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
return "hello world";
}
}
2. MainActivity.java 增加代码
增加 webView.addJavascriptInterface 启用javascript等 之前都设置了
//webview绑定java事件 h5中js通过android关键字引用new JsInteration() 调用JsInteration的方法
webView.addJavascriptInterface(new JsInteration(textToSpeech), “android”);
package com.bsoft.myapplication;
import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.Window;
import a