开发者

Android PhoneStateListener returns past calls

开发者 https://www.devze.com 2023-03-08 13:17 出处:网络
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 expecte

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);
}


pr开发者_Python百科ivate 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);
    }
};


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消