Tuesday, 4 October 2016

Android - Detect calls using PhoneStateListener



You can detect received calls in android. The Android API provides you three states that you can track for a call.

1) CALL_STATE_IDLE = The phone is idle
2) CALL_STATE_OFFHOOK = A call is in progress (user is talking)
3) CALL)STATE_RINGING = There is an incoming call and the user has not yet picked up the call


Declare a receiver in your manifest.xml :

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

<receiver android:name=".ServiceReceiver">
    <intent-filter>
      <action android:name="android.intent.action.PHONE_STATE" />
   </intent-filter>
</receiver>


Extend the PhoneStateListener Class and create your own subclass and implement your logic in the OnCallStateChanged method :

import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.webkit.WebView;

public class MyPhoneStateListener extends PhoneStateListener {

    public static Boolean phoneRinging = false;

    public void onCallStateChanged(int state, String incomingNumber) {

        switch (state) {
        case TelephonyManager.CALL_STATE_IDLE:
            Log.d("DEBUG", "IDLE");
            phoneRinging = false;
            break;
        case TelephonyManager.CALL_STATE_OFFHOOK:
            Log.d("DEBUG", "OFFHOOK");
            phoneRinging = false;
            break;
        case TelephonyManager.CALL_STATE_RINGING:
            Log.d("DEBUG", "RINGING");
            phoneRinging = true;

            break;
        }
    }

}

In the onReceive() method of your receiver, add your custom phone state listener to the telephony manager to listen for changes.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
public class ServiceReceiver extends BroadcastReceiver {
    TelephonyManager telephony;

    public void onReceive(Context context, Intent intent) {
        MyPhoneStateListener phoneListener = new MyPhoneStateListener();
        telephony = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        telephony.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
    }

    public void onDestroy() {
        telephony.listen(null, PhoneStateListener.LISTEN_NONE);
    }
}


Make sure you unregister your listener by passing LISTEN_NONE or else you will keep adding new listeners to the telephony manager.

Note: It is not possible to detect all instances of missed calls using this method even though some stackoverflow answers claim to do so. 


No comments:

Post a Comment