React Native中适配Java AlertDialog实现NearbyConnection连接确认咨询
适配React Native的手动连接确认实现方案
RN的跨层通信默认是异步的,不存在Java层同步调用JS函数并立刻获取返回结果的实现,以下是两种可行的落地方案:
方案1:修复原有Native弹窗崩溃问题
原有Java代码崩溃的核心原因是Nearby Connection的回调默认不在Android UI线程执行,直接弹出AlertDialog会触发线程异常,修改为切到UI线程执行即可:
// 先切换到Android主线程执行弹窗逻辑 runOnUiThread(() -> { new AlertDialog.Builder(context) .setTitle("Accept connection to " + info.getEndpointName()) .setMessage("Confirm the code matches on both devices: " + info.getAuthenticationDigits()) .setPositiveButton( "Accept", (DialogInterface dialog, int which) -> Nearby.getConnectionsClient(context) .acceptConnection(endpointId, payloadCallback)) .setNegativeButton( "Refuse", (DialogInterface dialog, int which) -> Nearby.getConnectionsClient(context).rejectConnection(endpointId)) .setIcon(android.R.drawable.ic_dialog_alert) .setCancelable(false) // 禁止点击空白关闭弹窗,避免连接状态挂起 .show(); });
方案2:Native回调到JS层处理交互(更符合RN开发规范)
该方案将交互逻辑统一放到JS层实现,适配RN的技术栈特点,实现步骤如下:
- 第一步:在RN原生模块中定义事件发射器,收到Nearby连接请求时把核心参数发送到JS层
// 原生模块发送事件到JS层 private void sendConnectionRequestEvent(String endpointId, String endpointName, String authDigits) { WritableMap params = Arguments.createMap(); params.putString("endpointId", endpointId); params.putString("endpointName", endpointName); params.putString("authDigits", authDigits); reactContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("nearby_connection_request", params); }
- 第二步:在Nearby的
onConnectionInitiated回调中调用上述方法发送事件,暂不执行接受/拒绝逻辑 - 第三步:在原生模块中暴露两个方法给JS调用,对应处理连接结果
@ReactMethod public void acceptConnection(String endpointId) { Nearby.getConnectionsClient(context) .acceptConnection(endpointId, payloadCallback); } @ReactMethod public void rejectConnection(String endpointId) { Nearby.getConnectionsClient(context).rejectConnection(endpointId); }
- 第四步:JS侧监听事件,弹出RN确认框,用户选择后调用对应原生方法
// JS侧业务代码 import { DeviceEventEmitter, Alert, useEffect } from 'react-native'; import NearbyModule from './NativeModules/NearbyModule'; useEffect(() => { // 监听Nearby连接请求事件 const eventSub = DeviceEventEmitter.addListener( 'nearby_connection_request', (data) => { Alert.alert( `Accept connection to ${data.endpointName}`, `Confirm the code matches on both devices: ${data.authDigits}`, [ { text: 'Refuse', onPress: () => NearbyModule.rejectConnection(data.endpointId) }, { text: 'Accept', onPress: () => NearbyModule.acceptConnection(data.endpointId) } ], { cancelable: false } ) } ) // 组件卸载时移除监听 return () => eventSub.remove() }, [])
内容的提问来源于stack exchange,提问作者parice02
相关产品推荐
相关产品推荐

