我创建了一个android应用程序,并在android webView上加载了一个html文件。加载成功,工作正常。
class MainActivity : AppCompatActivity() {
private lateinit var myAndroidWebView: WebView;
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setWebviewDetails();
}
private fun setWebviewDetails(){
//if(!::myAndroidWebView.isInitialized){
myAndroidWebView = findViewById(R.id.webView);
//}
myAndroidWebView.settings.javaScriptEnabled = true;
myAndroidWebView.loadUrl("file:///android_asset/App/index.html");
myAndroidWebView.addJavascriptInterface(WebAppInterface(this), "AndroidApp");
}
public fun testMessage(param: String){
println("Interface call-2")
myAndroidWebView.post(Runnable {
val str = "xxxXXXXXXXXXXXXXx $param"
myAndroidWebView.loadUrl("javascript:Application.UserInterface.sample('$str')")
})
println("Interface call-3")
}
}现在,我想向Android应用程序发送消息给JS,反之亦然。我在HTML中有一个按钮,并对函数进行了优化
public fun showToast(toast: String) {}通过使用HTML视图,工作正常的AndroidApp.showToast("hello");和我正在接到JS对Android接口函数showToast()的调用。
现在,根据JS的请求,我希望从Android获得一些值,并将其发送回JS。我有一个接口,在HTML的触发器按钮上,我收到了以下接口函数的调用。在试图调用MainActivity中的方法时,会成功地触发public fun testMessage(param: String){}。
问题:我试图通过使用,向JS发送数据
myAndroidWebView.loadUrl("javascript:Application.UserInterface.sample('$str')")这是我的错误。
W/System.err: kotlin.UninitializedPropertyAccessException: lateinit property myAndroidWebView has not been initialized我该怎么解决。谢谢。
/** Instantiate the interface and set the context */
class WebAppInterface(private val mContext: Context) {
var mainActivity:MainActivity = MainActivity();
/** Show a toast from the web page */
@JavascriptInterface
public fun showToast(toast: String) {
println("Interface call-1")
mainActivity.testMessage(mContext,toast);
}
}发布于 2022-06-23 09:11:05
引发lateinit property not initialized异常是因为您试图在WebInterface中创建MainActivity实例。var mainActivity:MainActivity = MainActivity();
创建和加载您的活动是Android系统的工作。你永远不应该尝试发起一项活动。
这里,您的代码的一个粗略的改进。试着让它适应你的需要。
interface JsCommunicator {
fun testMessage(param: String)
}
class WebAppInterface(private val communicator: JsCommunicator) {
@JavascriptInterface
fun showToast(toast: String) {
communicator.testMessage(toast)
}
}
class YourMainActivity : JsCommunicator {
// ...
private lateinit var myAndroidWebView: WebView
override fun testMessage(param: String) {
println("Interface call-2")
myAndroidWebView.post(Runnable {
val str = "xxxXXXXXXXXXXXXXx $param"
myAndroidWebView.loadUrl("javascript:Application.UserInterface.sample('$str')")
})
println("Interface call-3")
}
}发布于 2022-06-23 12:43:51
You are accessing web-view without initialising it.
call setWebviewDetails() first then testMessage()
or you can make webview nullable like this
private var myAndroidWebView: WebView? = null;
also you need to call startActivity() to create Activity not by
creating objects as this is framework class managed by Android
System.https://stackoverflow.com/questions/72726722
复制相似问题