前言
最近因為實習(xí)接觸了React Native,有個要求是RN需要調(diào)用Android的原生控件來使用,結(jié)果百度一查發(fā)現(xiàn)許多都是很早之前的教程了(RN的更新速度比較快),就連RN的中文論壇也不是最新的,我這里就在此記錄一下,使用的版本為0.62.2。
封裝VideoView
我們以封裝Android的VideoView為例子,根據(jù)官網(wǎng)教程(不推薦看中文版)需要5個步驟。
- 1.創(chuàng)建一個ViewManager的子類。
- 2.實現(xiàn)
createViewInstance()方法。 - 3.導(dǎo)出視圖的屬性設(shè)置器:使用@ReactProp(或@ReactPropGroup)注解。
- 4.把這個視圖管理類注冊到應(yīng)用程序包的createViewManagers里。
- 5.實現(xiàn) JavaScript模塊。
首先在創(chuàng)建完RN項目,在Android工程下用Android Studio打開來進(jìn)行開發(fā),新建一個ReactVideoManager類來繼承SimpleViewManager。
public class ReactVideoManager extends SimpleViewManager<MyPlay> {
@NonNull
@Override
public String getName() {
return "MyVideoView";
}
@NonNull
@Override
protected MyPlay createViewInstance(@NonNull ThemedReactContext reactContext) {
return new MyPlay(reactContext);
}
}
這里需要重寫兩個方法,getName()是返回這個自定義控件的名字來給RN調(diào)用,而createViewInstance()返回的是要封裝的控件,這個繼承類也需要一個填入一個泛型,就是你要封裝的組件,這個MyPlay就是我自己封裝的VideoView,可以拿TextView來進(jìn)行嘗試。
接下來就是要導(dǎo)出屬性給RN進(jìn)行調(diào)用了,比如說視頻播放器的加載地址都是放在RN那里去進(jìn)行自由的調(diào)用,而不是在Android原生里面寫死,我們在ReactVideoManager類下面寫上以下代碼:
/**
* 視頻加載url
*
* @param videoView
* @param url
*/
@ReactProp(name = "videoUrl")
public void setUrl(MyPlay videoView, String url) {
videoView.setVideoPath(url);
videoView.start();
}
這個必須返回值為空而且是public權(quán)限的,然后添加上ReactProp注解,這個注解里面的name代表著RN可以調(diào)用這個名字來進(jìn)行放入一個String類型的值,注意第一個參數(shù)必須也是createViewInstance和泛型創(chuàng)建和相同的參數(shù)。然后接下來我們在創(chuàng)建一個ReactVideoPackage類繼承ReactPackage來把這個ReactVideoManager注冊進(jìn)去。
public class ReactVideoPackage implements ReactPackage {
@NonNull
@Override
public List<NativeModule> createNativeModules(@NonNull ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@NonNull
@Override
public List<ViewManager> createViewManagers(@NonNull ReactApplicationContext reactContext) {
return Arrays.asList(
new ReactVideoManager()
);
}
}
createNativeModules()是注冊模塊的,createViewManagers()是注冊管理器的,如果想要注冊多個模塊就在List里面多個添加就行,沒有要注冊的要寫成Collections.emptyList()。接下來就是在RN里面進(jìn)行封裝這個視頻組件了,創(chuàng)建一個Video.js,代碼如下:
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {
requireNativeComponent, View, UIManager,
findNodeHandle,
} from 'react-native';
var RCT_VIDEO_REF = 'MyVideoView';
class VideoView extends Component {
constructor(props) {
super(props);
}
render() {
return <RCTVideoView
{...this.props}
ref={RCT_VIDEO_REF}
/>;
};
}
VideoView.propTypes = {
videoUrl: PropTypes.string,
...View.propTypes,
};
var RCTVideoView = requireNativeComponent('MyVideoView', VideoView);
module.exports = VideoView;
我們在VideoView.propTypes可以將屬性videoUrl進(jìn)行導(dǎo)出給外界調(diào)用,類型是string,當(dāng)然也有其他對應(yīng)的屬性。
Boolean -> Bool
Integer -> Number
Double -> Number
Float -> Number
String -> String
Callback -> function
ReadableMap -> Object
ReadableArray -> Array
最后我們在需要調(diào)用的地方調(diào)用就完畢了。
import React, {Component} from 'react';
import {Text, View, TouchableOpacity, StyleSheet, Image} from 'react-native';
import MyVideView from './Video';
export default class HelloWorldApp extends Component {
render() {
return (
<View style={styles.container}>
<MyVideView
ref={(video) => {
this.video = video;
}}
videoUrl={'https://wyhouse.oss-cn-beijing.aliyuncs.com/test/V00604-153602.mp4'}
style={{height: 200, width: 380, background: 'transparent'}}/>
<View style={{height: 90, flexDirection: 'row', justifyContent: 'flex-start'}}>
<TouchableOpacity style={{marginLeft: 10}} onPress={this.onPressPauseOrStart.bind(this)}>
<Text>測試按鈕</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'space-between',
},
});
Android向RN發(fā)送事件
封裝完成了,通過以上方法,就可以導(dǎo)出各種設(shè)置屬性來給RN使用,但是我要獲取到一些事件該怎么辦呢,比如視頻長度,進(jìn)度條之類的東西該怎么辦呢。我們可以通過RN的一系列方法來實現(xiàn),首相讓VideoView實現(xiàn)MediaPlayer.OnPreparedListener監(jiān)聽,然后輸入以下代碼:
@Override
public void onPrepared(MediaPlayer mp) {
int duration = mp.getDuration();
//向js發(fā)送事件
WritableMap event = Arguments.createMap();
event.putInt("duration", duration);
ReactContext reactContext = (ReactContext) getContext();
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
getId(), //綁定id
"topChange", //注意這里是發(fā)給RN的事件名稱,對應(yīng)RN上面的onchange事件
event //要傳的值,類似Bundle
);
}
然后在Video.js添加onchange事件
_onChange(event) {
if (!this.props.onPrepared) {
return;
}
this.props.onPrepared(event.nativeEvent.duration);//這里獲取到傳過來的值,就是對應(yīng)的key
}
render() {
return <RCTVideoView
{...this.props}
ref={RCT_VIDEO_REF}
onChange={this._onChange.bind(this)}
/>;
};
VideoView.propTypes = {
videoUrl: PropTypes.string,
onPrepared: PropTypes.func,
...View.propTypes,
};
var RCTVideoView = requireNativeComponent('MyVideoView', VideoView, {
nativeOnly: {onChange: true},
});//onChange屬性不想暴露給外面的話,就是通過nativeOnly來設(shè)置
module.exports = VideoView;
最后進(jìn)行調(diào)用:
//視頻時長
_onPrepared(duration) {
console.log('視頻時長 JS duration =' + duration);
}
<MyVideView
ref={(video) => {
this.video = video;
}}
videoUrl={'https://wyhouse.oss-cn-beijing.aliyuncs.com/test/V00604-153602.mp4'}
onPrepared={this._onPrepared}
style={{height: 200, width: 380, background: 'transparent'}}/>
接著你就可以在Android studio Logcat中看到RN輸出的信息了。

但是如果還有其他的事件怎么辦,不可能都只能用onchange事件吧,這里我們就可以自定義事件,只需要重寫ReactVideoManager下的getExportedCustomBubblingEventTypeConstants()方法就好,比如說實時獲取進(jìn)度條。
/**
* 新的自定義事件
*
* @return
*/
@Nullable
@Override
public Map<String, Object> getExportedCustomBubblingEventTypeConstants() {
return MapBuilder.<String, Object>builder().put(
"onProgress", MapBuilder.of("phasedRegistrationNames", MapBuilder.of("bubbled", "onProgress"))).build();
}
phasedRegistrationNames是規(guī)定的字段不能改,這是按照最新文檔寫出來的,網(wǎng)上找的都是老版而且不生效(都是踩出來的坑?。┙酉聛硪彩且粯拥?,比如我通過Handler和Runnable來配合獲取實時進(jìn)度條:
@Override
public void run() {
int progress = videoView.getCurrentPosition();
WritableMap event = Arguments.createMap();
event.putInt("progress", progress);
dispatchEvent("onProgress", event);
if (videoView.isPlaying()) {
videoSeekBar.setProgress(videoView.getCurrentPosition());
}
mHandler.postDelayed(this, 1000);
}
/**
* 傳遞RN層事件
*
* @param eventName
* @param eventMap
*/
public void dispatchEvent(String eventName, WritableMap eventMap) {
ReactContext reactContext = (ReactContext) getContext();
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
getId(),
eventName,
eventMap
);
}
//然后在RN層寫入事件
_onProgress(event) {
if (!this.props.onProgress) {
return;
}
this.props.onProgress(event.nativeEvent.progress);
}
render() {
return <RCTVideoView
{...this.props}
ref={RCT_VIDEO_REF}
onChange={this._onChange.bind(this)}
onProgress={this._onProgress.bind(this)}
/>;
};
VideoView.propTypes = {
videoUrl: PropTypes.string,
onPrepared: PropTypes.func,
onProgress: PropTypes.func,
...View.propTypes,
};
//最后調(diào)用這個方法就完事了
onProgress={this._onProgress}
//時長進(jìn)度更新
_onProgress(progress) {
console.log('JS time = ' + progress);
}
