首页 > 解决方案 > 从本机服务发送广播到本机模块 React Native

问题描述

我正在尝试将广播从后台服务发送到本机模块,然后做出本机反应,但我无法让本机模块中的广播接收器接收广播。我的服务接收推送通知正常,发送广播时没有错误。

我的服务看起来像这样

public myService extends CustomService{
    public void sendBroadcastFunction(){
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this.getApplicationContext());
        Intent intent = new Intent("com.appName.NOTIFICATION");
        localBroadcastManager.sendBroadcast(intent);
    }

}

我的原生模块

public class myModule extends ReactContextBaseJavaModule{
    private BroadcastReceiver receiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent){
        Log.d("Houston", "we possibly have a notification");
        if(intent != null){
            Log.d("Houston", "we have a notification");
            Log.d("Houston", "broadcast receiver is working");
            //Toast.makeText(getReactApplicationContext(), "Notification received", Toast.LENGTH_LONG).show();
        }
    }
    };

    public myModule(ReactApplicationContext reactContext){
        super(reactContext);
        reactContext.startService(newIntent(reactContext, myService.class));
        IntentFilter filter = new IntentFilter("com.appName.NOTIFICATION");
        reactContext.registerReceiver(receiver, filter);
    }
}

标签: androidreact-native

解决方案


推荐阅读