How to detect when a user picks up a call in a Cordova plugin

I am working on a Cordova application, and I need to detect when a user picks up a phone call. Specifically, I want to know when the microphone is being used for the call (in call mode) without actually recording audio.

I created a custom Cordova plugin in Java, and I'm using the AudioManager to check if the system is in call mode. The plugin should be able to detect when the user picks up a call and notify the JavaScript side of the application.

Here is how I achieve this:

Java plugin code

package com.geek.monitor;

import org.json.JSONArray;

import android.content.Context;
import org.apache.cordova.*;
import org.json.JSONException;
import org.json.JSONObject;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.media.AudioFormat;

public class Monitor extends CordovaPlugin {
    private CallbackContext callbackContext;

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
        this.callbackContext = callbackContext;

        if (action.equals("checkMicrophoneStatus")) {
              checkMicrophoneStatus(callbackContext);
              return true;
        }

        return false;
    }

    private void checkMicrophoneStatus(CallbackContext callbackContext) {
        // Step 1: Check if the microphone is muted using AudioManager
        AudioManager audioManager = (AudioManager)    cordova.getActivity().getSystemService(Context.AUDIO_SERVICE);
        boolean isMuted = audioManager.isMicrophoneMute();

        if (isMuted) {
              // If the microphone is muted, return a failure response
              callbackContext.error("Microphone is muted or unavailable");
        } else {
              // Step 2: Check if the system is in call mode
              int mode = audioManager.getMode();

              if (mode == AudioManager.MODE_IN_CALL) {
                    // If the system is in call mode, the microphone is in use for          a call
                    callbackContext.success("Picked-up");
              } else {
                    // If not in call mode, the microphone is not in use for a call
                    callbackContext.success("Not in call use");
              }
        }
    }
}

Here is plugin JavaScript code

exports.checkMicrophoneStatus = function (successCallback, errorCallback) {
    exec(successCallback, errorCallback, 'Monitor', 'checkMicrophoneStatus');
}

This is how to call from js

cordova.plugins.Monitor.checkMicrophoneStatus(
    function (status) {
        console.log(status); // "Picked-up" or "Not in call use"
    },
    function (error) {
       
        console.error(error); // error message
    }
);

Upvotes: 0

Views: 37

Answers (0)

Related Questions