2

我在React Native上構建應用程序,我想使用Android Service NotificationListenerService。爲了從服務中獲取數據,我需要一臺廣播接收器。我如何在React Native環境中設置BroadcastReceiver?在React Native上設置Android BroadcastReceiver

+0

嘗試:https://facebook.github.io/react-native/docs/headless-js-android.html –

回答

5

我所做的是使用getJSModule

MyListener.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有關發送事件的詳細信息emit事件的方式。

+0

它工作?看來我不能實例化一個WritableMap對象。 – user3348949

+0

它實際上是'WritableNativeMap'。更新了我的答案。 – vinayr

+0

我很新,反應原生,所以我不完全理解eventListeners。顯然,在模塊上,編譯器找不到'this.reactContext'。這部分是否正確? – user3348949

相關問題