我正在 React Native 上构建应用程序,我想使用 Android 服务 NotificationListenerService。为了从服务中捕获数据,我需要一个广播接收器。如何在 React Native 环境中设置 BroadcastReceiver?
最佳答案
我的方法是使用getJSModule
emit
事件
我的监听器.java
public class MyListener extends NotificationListenerService {
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
if (sbn.getNotification().tickerText == null) {
return;
}
WritableNativeMap params = new WritableNativeMap();
params.putString("tickerText", sbn.getNotification().tickerText.toString());
params.putString("packageName", sbn.getPackageName());
MyModule.sendEvent("notificationReceived", params);
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {}
}
MyModule.java
public class MyModule extends ReactContextBaseJavaModule implements ActivityEventListener {
private static ReactApplicationContext reactContext;
public MyModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
reactContext.addActivityEventListener(this);
}
public static void sendEvent(String event, WritableNativeMap params) {
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(event, params);
}
.......
}
检查 here有关发送事件的更多详细信息。
关于android - 在 React Native 上设置 Android BroadcastReceiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42543141/