package com.centaurwarchief.smslistener;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.os.Build;
import android.provider.Telephony;

import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;

public class SmsListenerModule extends ReactContextBaseJavaModule implements LifecycleEventListener {
    private BroadcastReceiver mReceiver;

    public SmsListenerModule(ReactApplicationContext context) {
        super(context);
        context.addLifecycleEventListener(this);

        mReceiver = new SmsReceiver(context);
        registerReceiverIfNecessary(mReceiver);
    }

    private void registerReceiverIfNecessary(BroadcastReceiver receiver) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && getCurrentActivity() != null) {
            getCurrentActivity().registerReceiver(
                receiver,
                new IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)
            );

            return;
        }

        if (getCurrentActivity() != null) {
            getCurrentActivity().registerReceiver(
                    receiver,
                    new IntentFilter("android.provider.Telephony.SMS_RECEIVED")
            );
        }
    }

    private void unregisterReceiver(BroadcastReceiver receiver) {
        if (getCurrentActivity() != null) {
            getCurrentActivity().unregisterReceiver(receiver);
        }
    }

    @Override
    public void onHostResume() {
        registerReceiverIfNecessary(mReceiver);
    }

    @Override
    public void onHostPause() {
        unregisterReceiver(mReceiver);
    }

    @Override
    public void onHostDestroy() {
        unregisterReceiver(mReceiver);
    }

    @Override
    public String getName() {
        return "SmsListenerPackage";
    }
}

@@ -523,16 +523,66 @@
 eceiver;
+%0A    private boolean isReceiverRegistered = false;
 %0A%0A    pu
@@ -1156,17 +1156,57 @@
      );%0A
+            isReceiverRegistered = true;
 %0A
-
         
@@ -1440,32 +1440,73 @@
 %0A            );%0A
+            isReceiverRegistered = true;%0A
         %7D%0A    %7D%0A
@@ -1576,32 +1576,56 @@
 ) %7B%0A        if (
+isReceiverRegistered && 
 getCurrentActivi
@@ -1699,24 +1699,66 @@
 (receiver);%0A
+            isReceiverRegistered = false;%0A
         %7D%0A  

fix multiple unregisterReceiver calls; fixes #4