如何通过webview从React组件的构造函数执行Java函数



我正在制作一个视频聊天应用程序,它必须在我的android应用程序的网络视图中工作。

因此,我想要的是根据java将音频和视频设置为true或false。这意味着如果我点击ui按钮中的音频呼叫按钮,我应该将视频设置为false,反之亦然。

this.getUserMedia = navigator.mediaDevices.getUserMedia({
audio: true,
video: true
})

这是包含上述行的组件的完整代码。

import React, { Component } from 'react';
import MediaContainer from './MediaContainer'
import CommunicationContainer from './CommunicationContainer'
import { connect } from 'react-redux'
import store from '../store'
import io from 'socket.io-client'
class RoomPage extends Component {
constructor(props) {
super(props);
this.getUserMedia = navigator.mediaDevices.getUserMedia({
audio: true,
video: true
}).catch(e => alert('getUserMedia() error: ' + e.name))
this.socket = io.connect();
}
componentDidMount() {
this.props.addRoom();
}
render(){
return (
<div>
<MediaContainer media={media => this.media = media} socket={this.socket} getUserMedia={this.getUserMedia} />
<CommunicationContainer socket={this.socket} media={this.media} getUserMedia={this.getUserMedia} />
</div>
);
}
}
const mapStateToProps = store => ({rooms: new Set([...store.rooms])});
const mapDispatchToProps = (dispatch, ownProps) => (
{
addRoom: () => store.dispatch({ type: 'ADD_ROOM', room: ownProps.match.params.room })
}
);
export default connect(mapStateToProps, mapDispatchToProps)(RoomPage);

如果你能给我一个样本代码,请。我是React的新手,所以请尽可能明确。

您可以使用javascript来调用本机函数。

在android(java(中,创建一个将用作JavascriptInterface 的类

public class MyExecutorInterface {
Context mctxt;

MyExecutorInterface (Context c) {
mctxt= c;
}
@JavascriptInterface   // must be added for API 17 or higher
public void executeAction(String message) {
Toast.makeText(mctxt, message, Toast.LENGTH_SHORT).show();
}
}

当您声明您的webview时,启用javascript并传递负责执行操作的类。

MyExecutorInterface jsInt = new MyExecutorInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(jsInt, "JSInterface"); // JSInterface is what will be used in javascript

现在你可以用Javascript这样调用你的操作:

window.JSInterface.executeAction(message)