注册

手把手教你集成环信ReactNative离线推送(下)

点此链接查看:手把手教你集成环信ReactNative离线推送(上)

三、从原生将device_token 传到RN 并且绑定

1、原生调用方法


reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("deviceToken",jsonObject.toString());

通过PushModule 类进行传递,PushModule 代码如下:


package com.awesomeproject;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.xiaomi.mipush.sdk.MiPushClient;
import org.json.JSONException;
import org.json.JSONObject;

public class PushModule extends ReactContextBaseJavaModule {
private ReactApplicationContext reactContext;
public PushModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
}

@Override
public String getName() {
return "PushModule";
}
/**
从RN界面里面调用该方法
**/

@ReactMethod
public void getDeviceToken(){
MainApplication.getReactPackage().mModule.sendDataToJS( MiPushClient.getRegId(MainApplication.getContext()));


}

public void sendDataToJS(String deviceToken){
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("deviceToken",deviceToken);
jsonObject.put("deviceName","2882303761517520571");

} catch (JSONException e) {
throw new RuntimeException(e);
}

this.reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("deviceToken",jsonObject.toString());
}



}

2、RN 层进行获取数据


NativeModules.PushModule.getDeviceToken();
DeviceEventEmitter.addListener('deviceToken',(res)=>{
const goosid = JSON.parse(res);
deviceToken = goosid.deviceToken;
manufacturer = goosid.deviceName;
console.log('React Native界面,收到数据:',goosid);

3、获取到数据后调用环信RN sdk 方法进行绑定

ChatClient.getInstance().updatePushConfig(push);

js 代码如下

// 导入依赖库
import React, { useEffect } from 'react';
import {
DeviceEventEmitter,
NativeModules,
SafeAreaView,
ScrollView,
StyleSheet,
Text,
TextInput,
View,
} from 'react-native';
import {
ChatClient,
ChatMessage,
ChatMessageChatType,
ChatOptions,
ChatPushConfig,
} from 'react-native-chat-sdk';
// 创建 app
const App = () => {
// 进行 app 设置
const title = 'ChatQuickstart';
var deviceToken='';
var manufacturer='';
NativeModules.PushModule.getDeviceToken();
DeviceEventEmitter.addListener('deviceToken',(res)=>{
const goosid = JSON.parse(res);
deviceToken = goosid.deviceToken;
manufacturer = goosid.deviceName;
console.log('React Native界面,收到数据:',goosid);

})
const [appKey, setAppKey] = React.useState('1137220225110285#demo');
const [username, setUsername] = React.useState('p9');
const [password, setPassword] = React.useState('1');
const [userId, setUserId] = React.useState('');
const [content, setContent] = React.useState('');
const [logText, setWarnText] = React.useState('Show log area');

// 输出 console log 文件
useEffect(() => {
logText.split('\n').forEach((value, index, array) => {
if (index === 0) {
console.log(value);
}
});
}, [logText]);

// 输出 UI log 文件
const rollLog = text => {
setWarnText(preLogText => {
let newLogText = text;
preLogText
.split('\n')
.filter((value, index, array) => {
if (index > 8) {
return false;
}
return true;
})
.forEach((value, index, array) => {
newLogText += '\n' + value;
});
return newLogText;
});
};

// 设置消息监听器。
const setMessageListener = () => {
let msgListener = {
onMessagesReceived(messages) {
for (let index = 0; index < messages.length; index++) {
rollLog('received msgId: ' + messages[index].msgId);
}
},
onCmdMessagesReceived: messages => {},
onMessagesRead: messages => {},
onGroupMessageRead: groupMessageAcks => {},
onMessagesDelivered: messages => {},
onMessagesRecalled: messages => {},
onConversationsUpdate: () => {},
onConversationRead: (from, to) => {},
};

ChatClient.getInstance().chatManager.removeAllMessageListener();
ChatClient.getInstance().chatManager.addMessageListener(msgListener);
};

// SDK 初始化。
// 调用任何接口之前,请先进行初始化。
const init = () => {

let option = new ChatOptions({
autoLogin: false,
appKey: appKey
});
ChatClient.getInstance().removeAllConnectionListener();
ChatClient.getInstance()
.init(option)
.then(() => {
rollLog('init success');
this.isInitialized = true;
let listener = {
onTokenWillExpire() {
rollLog('token expire.');
},
onTokenDidExpire() {
rollLog('token did expire');
},
onConnected() {
rollLog('login success.');
setMessageListener();
},
onDisconnected(errorCode) {
rollLog('login fail: ' + errorCode);
},
};
ChatClient.getInstance().addConnectionListener(listener);
})
.catch(error => {
rollLog(
'init fail: ' +
(error instanceof Object ? JSON.stringify(error) : error),
);
});
};

// 注册账号。
const registerAccount = () => {
if (this.isInitialized === false || this.isInitialized === undefined) {
rollLog('Perform initialization first.');
return;
}
rollLog('start register account ...');
ChatClient.getInstance()
.createAccount(username, password)
.then(response => {
rollLog(`register success: userName = ${username}, password = ******`);
})
.catch(error => {
rollLog('register fail: ' + JSON.stringify(error));
});
};

// 用环信即时通讯 IM 账号和密码登录。
const loginWithPassword = () => {
if (this.isInitialized === false || this.isInitialized === undefined) {
rollLog('Perform initialization first.');
return;
}
rollLog('start login ...');
ChatClient.getInstance()
.login(username, password)
.then(() => {
rollLog('login operation success.');
let push = new ChatPushConfig({
deviceId:manufacturer,
deviceToken:deviceToken,

});
console.log("--------------------------------------------");
console.log(manufacturer);
console.log(deviceToken);
console.log("--------------------------------------------");
ChatClient.getInstance().updatePushConfig(push);
})
.catch(reason => {
rollLog('login fail: ' + JSON.stringify(reason));
});
};

// 登出。
const logout = () => {
if (this.isInitialized === false || this.isInitialized === undefined) {
rollLog('Perform initialization first.');
return;
}
rollLog('start logout ...');
ChatClient.getInstance()
.logout()
.then(() => {
rollLog('logout success.');
})
.catch(reason => {
rollLog('logout fail:' + JSON.stringify(reason));
});
};

// 发送一条文本消息。
const sendmsg = () => {
if (this.isInitialized === false || this.isInitialized === undefined) {
rollLog('Perform initialization first.');
return;
}
let msg = ChatMessage.createTextMessage(
userId,
content,
ChatMessageChatType.PeerChat,
);
const callback = new (class {
onProgress(locaMsgId, progress) {
rollLog(`send message process: ${locaMsgId}, ${progress}`);
}
onError(locaMsgId, error) {
rollLog(`send message fail: ${locaMsgId}, ${JSON.stringify(error)}`);
}
onSuccess(message) {
rollLog('send message success: ' + message.localMsgId);
}
})();
rollLog('start send message ...');
ChatClient.getInstance()
.chatManager.sendMessage(msg, callback)
.then(() => {
rollLog('send message: ' + msg.localMsgId);
})
.catch(reason => {
rollLog('send fail: ' + JSON.stringify(reason));
});
};

// UI 组件渲染。
return (
<SafeAreaView>
<View style={styles.titleContainer}>
<Text style={styles.title}>{title}</Text>
</View>
<ScrollView>
<View style={styles.inputCon}>
<TextInput
multiline
style={styles.inputBox}
placeholder="Enter appkey"
onChangeText={text => setAppKey(text)}
value={appKey}
/>
</View>
<View style={styles.buttonCon}>
<Text style={styles.btn2} onPress={init}>
INIT SDK
</Text>
</View>
<View style={styles.inputCon}>
<TextInput
multiline
style={styles.inputBox}
placeholder="Enter username"
onChangeText={text => setUsername(text)}
value={username}
/>
</View>
<View style={styles.inputCon}>
<TextInput
multiline
style={styles.inputBox}
placeholder="Enter password"
onChangeText={text => setPassword(text)}
value={password}
/>
</View>
<View style={styles.buttonCon}>
<Text style={styles.eachBtn} onPress={registerAccount}>
SIGN UP
</Text>
<Text style={styles.eachBtn} onPress={loginWithPassword}>
SIGN IN
</Text>
<Text style={styles.eachBtn} onPress={logout}>
SIGN OUT
</Text>
</View>
<View style={styles.inputCon}>
<TextInput
multiline
style={styles.inputBox}
placeholder="Enter the username you want to send"
onChangeText={text => setUserId(text)}
value={userId}
/>
</View>
<View style={styles.inputCon}>
<TextInput
multiline
style={styles.inputBox}
placeholder="Enter content"
onChangeText={text => setContent(text)}
value={content}
/>
</View>
<View style={styles.buttonCon}>
<Text style={styles.btn2} onPress={sendmsg}>
SEND TEXT
</Text>
</View>
<View>
<Text style={styles.logText} multiline={true}>
{logText}
</Text>
</View>
<View>
<Text style={styles.logText}>{}</Text>
</View>
<View>
<Text style={styles.logText}>{}</Text>
</View>
</ScrollView>
</SafeAreaView>
);
};

// 设置 UI。
const styles = StyleSheet.create({
titleContainer: {
height: 60,
backgroundColor: '#6200ED',
},
title: {
lineHeight: 60,
paddingLeft: 15,
color: '#fff',
fontSize: 20,
fontWeight: '700',
},
inputCon: {
marginLeft: '5%',
width: '90%',
height: 60,
paddingBottom: 6,
borderBottomWidth: 1,
borderBottomColor: '#ccc',
},
inputBox: {
marginTop: 15,
width: '100%',
fontSize: 14,
fontWeight: 'bold',
},
buttonCon: {
marginLeft: '2%',
width: '96%',
flexDirection: 'row',
marginTop: 20,
height: 26,
justifyContent: 'space-around',
alignItems: 'center',
},
eachBtn: {
height: 40,
width: '28%',
lineHeight: 40,
textAlign: 'center',
color: '#fff',
fontSize: 16,
backgroundColor: '#6200ED',
borderRadius: 5,
},
btn2: {
height: 40,
width: '45%',
lineHeight: 40,
textAlign: 'center',
color: '#fff',
fontSize: 16,
backgroundColor: '#6200ED',
borderRadius: 5,
},
logText: {
padding: 10,
marginTop: 10,
color: '#ccc',
fontSize: 14,
lineHeight: 20,
},
});

export default App;

注:需要再登录成功以后进行绑定

四、推送测试

1、push测试
如何查看绑定的证书信息:
登录环信console—>即时推送—>找到对应的用户id—>点击查看用户绑定推送证书(如下图)

如何测试推送
登录环信console—> 即时推送—>填写相关的内容—>发送预览—>确认推送

收到推送

2、离线消息测试
登录环信console—> 即时通讯—>用户管理—>找到对应的用户id—>发送rest 消息



至此,ReactNative 推送集成完成。

0 个评论

要回复文章请先登录注册