当我收到短信时,我正在尝试发送一条消息以响应本机。我确实需要帮助,而且我不知道我在做什么错!
这是我创建的用于管理发送事件以响应本机的模块。
public class SendEventModule extends ReactContextBaseJavaModule implements ActivityEventListener {
private static ReactApplicationContext reactContext;
//private static ReactInstanceManager sReactInstanceManager = null;
@Override
public String getName() {
return "SendEventModule";
}
public SendEventModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
reactContext.addActivityEventListener(this);
}
public static void test(String event, WritableNativeMap params) {
Log.e("TEST_ERROR", "This is just a test");
//final ReactContext context = sReactInstanceManager.getCurrentReactContext();
sendEvent((ReactApplicationContext) reactContext, event, params);
}
private static void sendEvent(ReactApplicationContext reactContext,String event, WritableNativeMap params) {
Log.e("TEST_ERROR", "we made it to send event");
//context = (ReactApplicationContext) this.reactContext;
//ReactContext currentContext = getReactApplicationContext();
if(reactContext != null) {
reactContext.getJSModule(RCTDeviceEventEmitter.class).emit(event, params);
} else {
try {
reactContext.getJSModule(RCTDeviceEventEmitter.class).emit(event, params);
}catch(Exception e) {
Log.e("TEST_ERROR", e.getMessage());
}
Log.e("TEST_ERROR", "React Context is not defined");
}
}
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {}
@Override
public void onNewIntent(Intent intent){}
}
这是我的SMS接收器,我正在尝试发出事件以响应本机
public class SmsBroadcastReceiver extends BroadcastReceiver {
private static ReactApplicationContext reactContext;
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
Toast.makeText(context, "Message Received Bitch!", Toast.LENGTH_SHORT).show();
//WritableMap params = Arguments.createMap();
//params.putString("eventProperty", "someValue");
WritableNativeMap params = new WritableNativeMap();
params.putString("eventProperty", "someValue");
try {
SendEventModule.test("EventReminder", params);
} catch (Exception e) {
Log.e( "EVENT_ERROR", e.getMessage() );
}
}
}
这是我的错误,很明显没有定义reactContext,我也不知道为什么
2019-10-14 12:44:56.604 17861-17861 / com.test E / TEST_ERROR:尝试调用虚拟方法'com.facebook.react.bridge.JavaScriptModule com.facebook.react.bridge.ReactApplicationContext.getJSModule (java.lang.Class)”上的空对象引用
这是我的本机屏幕的代码
import React from "react";
import {
Container,
Header,
Content,
Textarea,
Form,
Button,
Text,
Left,
Body,
Right,
Icon,
Title,
List,
ListItem,
Radio,
CheckBox,
Footer,
FooterTab,
Item,
Input } from "native-base";
import { GiftedChat } from 'react-native-gifted-chat';
import SendSMS from 'react-native-sms-x';
import { NativeEventEmitter, NativeModules, DeviceEventEmitter, TouchableOpacity, Image } from 'react-native';
import { Col, Row, Grid } from "react-native-easy-grid";
//import { setJSExceptionHandler, getJSExceptionHandler } from 'react-native-exception-handler';
class NewMessageScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
messages: [],
data: props.navigation.state.params.data
};
}
componentDidMount() {
this.setState({
messages: [
{
_id: 1,
text: 'Hello developer',
createdAt: new Date(),
user: {
_id: 2,
name: 'React Native',
avatar: 'https://placeimg.com/140/140/any',
},
},
],
});
const eventEmitter = new NativeEventEmitter(NativeModules.SendEventModule);
eventEmitter.addListener('EventReminder', (event) => {
console.log(event.eventProperty); // "someValue"
});
}
onSend(messages = []) {
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages),
}));
SendSMS.send(1, this.state.data.number, messages[0].text,
(msg)=>{
alert(JSON.stringify(msg));
}
);
}
headerTitle() {
//alert(JSON.stringify(this.state.data));
if(this.state.data) {
if (typeof this.state.data.displayName !== 'undefined') {
return this.state.data.displayName;
} else {
return this.state.data.first_name + " " + this.state.data.last_name;
}
} else {
return "Group Text";
}
}
render() {
return (
<Container>
<Header style={{ backgroundColor: '#234561'}} transparent>
<Body>
<Title style={{ justifyContent: 'center', width: '100%'}}>{ this.headerTitle() }</Title>
</Body>
</Header>
<Row size={1} style={{ backgroundColor: "#234561" }}>
<Col>
<TouchableOpacity
style={{
borderWidth:1,
borderColor:'rgba(0,0,0,0.2)',
alignItems:'center',
justifyContent:'center',
width:65,
height:65,
backgroundColor:'#fff',
borderRadius:50,
overflow: 'hidden',
poisition: 'absolute',
left: '50%',
marginLeft: -33,
top: '50%',
marginTop: -33,
elevation: 10
}}
>
<Image style={{ height: '100%', width: '100%'}} source={{ uri: 'https://icon-library.net/images/default-user-icon/default-user-icon-14.jpg' }} />
</TouchableOpacity>
</Col>
<Col>
<TouchableOpacity
style={{
borderWidth:1,
borderColor:'rgba(0,0,0,0.2)',
alignItems:'center',
justifyContent:'center',
width:90,
height:90,
backgroundColor:'#fff',
borderRadius:50,
overflow: 'hidden',
left: '50%',
marginLeft: -45,
top: '50%',
marginTop: -45,
elevation: 10
}}
>
<Image style={{ height: '100%', width: '100%'}} source={{ uri: 'https://icon-library.net/images/default-user-icon/default-user-icon-14.jpg' }} />
</TouchableOpacity>
</Col>
<Col>
<TouchableOpacity
style={{
borderWidth:1,
borderColor:'rgba(0,0,0,0.2)',
alignItems:'center',
justifyContent:'center',
width:65,
height:65,
backgroundColor:'#fff',
borderRadius:50,
overflow: 'hidden',
poisition: 'absolute',
left: '50%',
marginLeft: -33,
top: '50%',
marginTop: -33,
elevation: 10
}}
>
<Image style={{ height: '100%', width: '100%'}} source={{ uri: 'https://icon-library.net/images/default-user-icon/default-user-icon-14.jpg' }} />
</TouchableOpacity>
</Col>
</Row>
<Row size={4}>
<GiftedChat
messages={this.state.messages}
onSend={messages => this.onSend(messages)}
user={{
_id: 1,
}}
/>
</Row>
</Container>
);
}
}
export default NewMessageScreen;
请帮助!!!
答案 0 :(得分:0)
您在SendEventModule中有一个构造函数
public SendEventModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
reactContext.addActivityEventListener(this);
}
但是,您可以通过静态访问来调用方法,而无需首先通过构造函数来使SentEventModule完整。 在您的方法中,您尝试访问从未设置过的reactContext。
在Java中,必须将变量设置为非null。 e.G
String text;
// text == null
text = "awesome";
// text == "awesome";
也许这两个链接将帮助您解决问题: https://gist.github.com/renganatha10/96ce8c845d981008d2a76da756954b25 How to access Activity from a React Native Android module?
有关静态的进一步阅读:https://www.javatpoint.com/static-keyword-in-java
答案 1 :(得分:0)
我通过注册模块解决了这个问题;这发生在应用程序包的createNativeModules中。如果未注册模块,它将无法从JavaScript使用,并且将无法访问ReactApplicationContext !!!
public class SendEventPackage implements ReactPackage {
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new SendEventModule(reactContext));
return modules;
}
}
创建此包后,需要在MainApplication.java文件的getPackages方法中提供该包。
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
//packages.add(new SendEventModule(this)); // THIS IS THE WRONG WAY
packages.add(new SendEventPackage()); // <-- Add this line with your package name.
return packages;
}