Android – Detecting incoming call on android device with Cordova

androidcordova

I am new to learn to programme for Android. I was looking for a very long plug for the incoming call number. My search attempts were unsuccessful. I decided to create a plugin. I used as an example here are the sources:

Here's what I came up with:

package org.apache.cordova.plugin;

import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Date;
import android.content.BroadcastReceiver;
import android.content.Intent;


public class SignalStrength extends CordovaPlugin {

    CallStateListener ssListener;
    String Number;

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("go")) {   
            TelephonyManager tm = (TelephonyManager) cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE); 
            ssListener = new CallStateListener();
            tm.listen(ssListener, PhoneStateListener.LISTEN_CALL_STATE);
            callbackContext.success(name);
            return true;
        }

        return false;
    }


    class CallStateListener extends PhoneStateListener {

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    // called when someone is ringing to this phone
                    String Number= incomingNumber;
                    break;
            }
        }
    }

}

Manifest:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
...
<receiver android:name=".CallReceiver">
    <intent-filter>
        <action android:name="android.intent.action.PHONE_STATE" />
    </intent-filter>
</receiver>

But unfortunately returns NULL
Help me to understand.

Best Answer

I'm using this plugin:

https://github.com/renanoliveira/cordova-phone-call-trap

usage is very simple:

if (window.PhoneCallTrap) {
    PhoneCallTrap.onCall(function(state) {
        console.log("CHANGE STATE: " + state);

        switch (state) {
            case "RINGING":
                console.log("Phone is ringing");
                break;
            case "OFFHOOK":
                console.log("Phone is off-hook");
                break;

            case "IDLE":
                console.log("Phone is idle");
                break;
        }
    });
}