• 1
Votes
name

I'm trying to tap on the incoming call using a following background service in NativeScript and searching the incoming number in Firebase Database.

The firebase.query from nativescript-plugin-firebase code works fine if the application UI is visible or minimized in Android but when the application is closed (however, the service is running in background), it throws firebase.query: TypeError: Cannot read property 'child' of null error. Any Idea.

app/broadcastreceivers/NotificationEventReceiver.js:

var application = require("application");
var firebase = require("nativescript-plugin-firebase");
var incomingCallDetected = false;
var TelephonyManager = application.android.context.getSystemService(android.content.Context.TELEPHONY_SERVICE);

android.support.v4.content.WakefulBroadcastReceiver.extend("com.tns.broadcastreceivers.NotificationEventReceiver", {
  onReceive: function (context, intent) {
    if (intent.getAction() === 'android.intent.action.PHONE_STATE') {
       incomingCallDetected = true;
    }
  }
});

var callStateListener = android.telephony.PhoneStateListener.extend({
  onCallStateChanged: function (state, phoneNumber) {
    if (incomingCallDetected && state === 1) { // incoming call ringing
      firebase.query(
        function(result) {
          console.log(JSON.stringify(result)); 
        },
        "/calls",
        {
          singleEvent: true,
          orderBy: {
            type: firebase.QueryOrderByType.CHILD,
            value: 'PhoneNumber'
          },
          range: {
            type: firebase.QueryRangeType.EQUAL_TO,
            value: phoneNumber.replace(/s+/g, '').substr(-10)
          }
        }
      );
      incomingCallDetected = false;
    }
  }
});
TelephonyManager.listen(new callStateListener(), android.telephony.PhoneStateListener.LISTEN_CALL_STATE);

Update: This line in nativescript-plugin-firebase causes the problem because firebaseInstance does not persist in the service once the application is closed.