Hank McLaughlin
Hank McLaughlin

Reputation: 41

Android PhoneStateListener returns past calls

Im using a PhoneStateListener to find out when the phone is in an active call and when the call ends and log wether it was in incoming or outgoing call. when I install the listener it works as expected on the first call. Affter that although it still works it returns info for the fist call as well as the second call, On the 3rd call it returns info for 3 calls etc. How do I only get info for the active call? Code below, any help is appreciated

@Override
public void onReceive(Context context, Intent intent) {
    mContext = context;
    mIntent = intent;
    mlocManager= (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
    mlocListener = new MyLocationListener();

    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    int events = PhoneStateListener.LISTEN_CALL_STATE;
    tm.listen(phoneStateListener, events);
}


private final PhoneStateListener phoneStateListener = new PhoneStateListener() {
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        Log.e("GO", incomingNumber);



        String number = null;
        String callState = "UNKNOWN";
        switch (state) {
        case TelephonyManager.CALL_STATE_IDLE:
            callState = "IDLE";
            break;
        case TelephonyManager.CALL_STATE_RINGING:
            // -- check international call or not.
            callState = "INCOMING";
            number = incomingNumber;

            break;
        case TelephonyManager.CALL_STATE_OFFHOOK:
            number = mIntent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

            callState = "OUTGOING";

            break;
        }




        super.onCallStateChanged(state, incomingNumber);
    }
};

Upvotes: 1

Views: 2261

Answers (1)

Hank McLaughlin
Hank McLaughlin

Reputation: 41

Answering my own question. This code creates multiple listeners for every call. I have to stop the listener after the call ends with the below line

tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);

Upvotes: 3

Related Questions