正如标题所暗示的,即使在我的 react-native 应用程序被杀死/后台模式之后,我也试图从我连接的 BLE 外围设备监听点击事件。
连接后,我的 BLE 外围设备上有一个通知订阅,每次我按下设备上的按钮时,我的应用都会收到通知。即使用户终止应用程序,我也希望此订阅能够持续。
该应用程序在前台和非活动状态下运行良好,但是当我在 iOS 上终止该应用程序时,它停止响应按钮单击。在 android 上,我找到了一个库react-native-background-actions来帮助解决这个问题。这是当前在android上工作的背景代码。
import BackgroundJob from "react-native-background-actions";
playing = BackgroundJob.isRunning();
const sleep = (time) =>
new Promise((resolve) => setTimeout(() => resolve(), time));
BackgroundJob.on("expiration", () => {
console.log("iOS: I am being closed!");
});
const taskRandom = async (taskData) => {
if (Platform.OS === "ios") {
console.warn(
"This task will not keep your app alive in the background by itself, use other library like react-native-track-player that use audio,",
"geolocalization, etc. to keep your app alive in the background while you excute the JS from this library."
);
}
await new Promise(async (resolve) => {
// For loop with a delay
const { delay } = taskData;
console.log(BackgroundJob.isRunning(), delay);
for (let i = 0; BackgroundJob.isRunning(); i++) {
console.log("Ran -> ", i);
// await BackgroundJob.updateNotification({
// taskDesc: "Emergency -> " + i,
// });
await sleep(delay);
}
});
};
const options = {
taskName: "Example",
taskTitle: "ExampleTask title",
taskDesc: "ExampleTask desc",
taskIcon: {
name: "ic_launcher",
type: "mipmap",
},
color: "#ff00ff",
linkingURI: "exampleScheme://chat/jane",
parameters: {
delay: 30000,
},
};
/**
* Toggles the background task
*/
export const toggleBackground = async () => {
playing = !playing;
if (playing) {
try {
console.log("Trying to start background service");
await BackgroundJob.start(taskRandom, options);
console.log("Successful start!");
} catch (e) {
console.log("Error", e);
}
} else {
console.log("Stop background service");
await BackgroundJob.stop();
}
};
我尝试阅读iOS 应用程序的核心蓝牙后台处理,并在我的启动方法上添加了一个恢复标识符,如下所示:
BleManager.start({
showAlert: true,
restoreIdentifierKey: "IDENTIFIER",
queueIdentifierKey: "IDENTIFIER",
}).then(() => {
console.log("Module initialized");
});
有没有人对如何在应用程序处于后台时保留订阅有任何建议?react-native-background-actions建议使用音频或地理位置库,但这些与我的应用程序无关。
任何帮助将不胜感激。