我已经制作了一个React Native App,可以使用Android上的前台服务扫描BLE设备。我遇到的问题是互联网连接的丢失。互联网可用后,将不执行在互联网不可用时添加到队列中的待处理操作。
一旦检测到信标,我就会使用NativeModules将事件发送到React Native,接收到事件后,我会检查互联网是否可用。如果不是,则将其存储在队列中。
const didEnterRegion = async (store, beacons) => {
const { isConnected } = store.getState().connection;
if (isConnected) {
store.dispatch({
type: REQUEST_CHECKIN,
payload: beacons,
});
} else {
NativeModules.BeaconFinder.sendNotification(
'Looks like you entered a venue, but the internet is not reachable.',
beacons.uuid.toString(),
);
store.dispatch({
type: ADD_ACTION_TO_QUEUE,
name: REQUEST_CHECKIN,
payload: beacons,
});
}
};
在App.js中,我不断检查互联网连接。如果可用,我将执行队列中的所有操作。
export default class App extends Component {
componentDidMount() {
const unsubscribe = NetInfo.addEventListener(state => {
this._handleConnectionChange(state.isInternetReachable);
});
}
componentWillUnmount() {
//unsubscribe();
}
_handleConnectionChange = isConnected => {
if (isConnected && _.size(store.getState().connection.actionQueue) > 0) {
let queue = store.getState().connection.actionQueue;
_.map(queue, action => {
console.log(action);
store.dispatch({
type: action.name,
payload: action.payload
});
});
}
store.dispatch({
type: CHANGE_CONNECTION_STATUS,
isConnected
});
};
render...
}
这在应用程序位于前台时有效,但是当应用程序从任务切换器中被杀死时,代码将随机执行,即有时可以正常工作,有时不起作用。