Question Detail

I have a plugin where i can read phone states but it is limited to status ringing, off hook, idle. I want to get incoming phone number through cordova plugins.


Thread Reply

alex levine

- 5 months ago

In Android Java

Create a Broadcast receiver say ServiceReceiver assign its action in Manifest.

<receiver android:name=".CallReceiver" >
    <intent-filter>
        <action android:name="android.intent.action.PHONE_STATE" /> //to receive only phone state Broadcast
    </intent-filter>
</receiver>

Add a PhoneStateListener to your TelephonyManager, PhoneStateListener having override onCallStateChanged() with Incoming number parameter. Thats it.

ServiceReceiver.Java

public class CallReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, Intent intent) {
        TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        telephony.listen(new PhoneStateListener(){
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                super.onCallStateChanged(state, incomingNumber);
                System.out.println("incomingNumber : "+incomingNumber);
            }
        },PhoneStateListener.LISTEN_CALL_STATE);
    }
}

Anonymous

- 5 months ago

try this for getting the Mobile number of Incoming Call

This plugin allows your application to monitor changes in the phone's state (RINGING, OFFHOOK and IDLE) so that you can respond to them appropriately (pause your Media stream, etc).

Add the plugin much like any other:

  1.  Add the PhoneListener.js file to your 'assets/www' folder
    
  2.  Create an 'org/devgeeks' folder under 'src' and add the PhoneListener.java file to it
    
  3.  Add the PhoneListener.js to your html file. eg: `<script type="text/javascript" charset="utf-8" src="PhoneListener.js"></script>`
    
  4.  Add the plugin to the 'res/xml/plugins.xml' file. eg: `<plugin name="PhoneListener" value="org.devgeeks.PhoneListener"/>`
    
  5.  Make sure you have allowed the permission 'READ_PHONE_STATE' in your 'AndroidManifest.xml. eg: `<uses-permission android:name="android.permission.READ_PHONE_STATE" />`
    

Example

function onDeviceReady()
{
	PhoneListener.start(onPhoneStateChanged,onError);
	// or...
	// PhoneListener.stop(onSuccess,onError);
}

function onPhoneStateChanged(phoneState) 
{
	switch (phoneState) {
		case "RINGING":
			console.log('Phone is ringing.');
			break;
		case "OFFHOOK":
			console.log('Phone is off the hook.');
			break;
		case "IDLE":
			console.log('Phone has returned to the idle state.');
			break;
		default:
			// no default...
	}
}

function onError(error) {
	// do something...
}
function onSuccess() {
	// do something else...
}

PhoneListener.java

import org.json.JSONArray;
   
  import android.content.BroadcastReceiver;
  import android.content.Context;
  import android.content.Intent;
  import android.content.IntentFilter;
  import android.telephony.TelephonyManager;
  import android.util.Log;
   
  import org.apache.cordova.api.CordovaInterface;
  import org.apache.cordova.api.Plugin;
  import org.apache.cordova.api.PluginResult;
   
  /**
  * @author Tommy-Carlos Williams,
  * Huge chunks lifted/adapted from the NextworkManager core PhoneGap plugin
  */
  public class PhoneListener extends Plugin {
   
  public static final String TYPE_NONE = "NONE";
  private static final String LOG_TAG = "PhoneListener";
   
  private String phoneListenerCallbackId;
   
  BroadcastReceiver receiver;
   
  /**
  * Constructor.
  */
  public PhoneListener() {
  this.receiver = null;
  }
   
  /**
  * Sets the context of the Command. This can then be used to do things like
  * get file paths associated with the Activity.
  *
  * @param ctx The context of the main Activity.
  */
  public void setContext(CordovaInterface ctx) {
  super.setContext(ctx);
  this.phoneListenerCallbackId = null;
   
  // We need to listen to connectivity events to update navigator.connection
  IntentFilter intentFilter = new IntentFilter() ;
  intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
  if (this.receiver == null) {
  this.receiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
  if(intent != null && intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
  // State has changed
  String phoneState = intent.hasExtra(TelephonyManager.EXTRA_STATE) ? intent.getStringExtra(TelephonyManager.EXTRA_STATE) : null;
  String state;
  // See if the new state is 'ringing', 'off hook' or 'idle'
  if(phoneState != null && phoneState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
  // phone is ringing, awaiting either answering or canceling
  state = "RINGING";
  Log.i(LOG_TAG,state);
  } else if (phoneState != null && phoneState.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
  // actually talking on the phone... either making a call or having answered one
  state = "OFFHOOK";
  Log.i(LOG_TAG,state);
  } else if (phoneState != null && phoneState.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
  // idle means back to no calls in or out. default state.
  state = "IDLE";
  Log.i(LOG_TAG,state);
  } else {
  state = TYPE_NONE;
  Log.i(LOG_TAG,state);
  }
  updatePhoneState(state,true);
  }
  }
  };
  // register the receiver... this is so it doesn't have to be added to AndroidManifest.xml
  cordova.getActivity().registerReceiver(this.receiver, intentFilter);
  }
  }
   
  /**
  * Create a new plugin result and send it back to JavaScript
  *
  * @param phone state sent back to the designated success callback
  */
  private void updatePhoneState(String phoneState, boolean keepCallback) {
  if (this.phoneListenerCallbackId != null) {
  PluginResult result = new PluginResult(PluginResult.Status.OK, phoneState);
  result.setKeepCallback(keepCallback);
  this.success(result, this.phoneListenerCallbackId);
  }
  }
   
  /* (non-Javadoc)
  * @see com.phonegap.api.Plugin#execute(java.lang.String, org.json.JSONArray, java.lang.String)
  */
  @Override
  public PluginResult execute(String action, JSONArray args, String callbackId) {
  PluginResult.Status status = PluginResult.Status.INVALID_ACTION;
  String result = "Unsupported Operation: " + action;
  // either start or stop the listener...
  if (action.equals("startMonitoringPhoneState")) {
  if (this.phoneListenerCallbackId != null) {
  return new PluginResult(PluginResult.Status.ERROR, "Phone listener already running.");
  }
  this.phoneListenerCallbackId = callbackId;
  PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
  pluginResult.setKeepCallback(true);
  return pluginResult;
  }
  else if (action.equals("stopMonitoringPhoneState")) {
  removePhoneListener();
  this.updatePhoneState("", false); // release status callback
  this.phoneListenerCallbackId = null;
  return new PluginResult(PluginResult.Status.NO_RESULT);
  }
   
  return new PluginResult(status, result); // no valid action called
  }
   
  /**
  * Stop the phone listener receiver and set it to null.
  */
  private void removePhoneListener() {
  if (this.receiver != null) {
  try {
  this.ctx.getContext().unregisterReceiver(this.receiver);
  this.receiver = null;
  } catch (Exception e) {
  Log.e(LOG_TAG, "Error unregistering phone listener receiver: " + e.getMessage(), e);
  }
  }
  }
   
  /**
  * Stop phone listener receiver.
  */
  public void onDestroy() {
  removePhoneListener();
  }
   
  }

 

 

PhoneListener.js

 

 

var PhoneListener = {
  start: function(successCallback, failureCallback) {
  return cordova.exec(
  successCallback,
  failureCallback,
  'PhoneListener',
  'startMonitoringPhoneState',
  []); // no arguments required
  },
  stop: function(successCallback, failureCallback) {
  return cordova.exec(
  successCallback,
  failureCallback,
  'PhoneListener',
  'stopMonitoringPhoneState',
  []); // no arguments required
  }
  };

 

for more: https://github.com/devgeeks/PhoneListener

Anonymous

- 5 months ago

If you looking for the incoming call, this is not possible at all on iOS due to each app being sandboxed.

On Android, you would need to create your own plugin or modify an existing one.

Here's one that listens for incoming calls:

https://github.com/devgeeks/PhoneListener