Memory Leak on using PhoneStateListener

447 views Asked by At

I am trying to use PhoneStateListener to notify my application when an incoming call triggers so as to perform some action. I register my PhoneStateListener in onResume() method of my activity as follows.

    @Override
    protected void onResume() {
     super.onResume();
     tmgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
     incomingCallListener=new IncomingCallListener();
     tmgr.listen(incomingCallListener, phoneStateListener.LISTEN_CALL_STATE);
    }

onPause() method of my activity i remove the listener using the following code.

     @Override
     protected void onPause() {
       super.onPause();
        incomingCallListener=null;
        tmgr.listen(incomingCallListener, PhoneStateListener.LISTEN_NONE);
        tmgr=null;
     }

My Incoming class is defined as an inner class in the same activity as follows:

    public class IncomingCallListener extends PhoneStateListener {

      public IncomingCallListener() {
      }

      @Override
      public void onCallStateChanged(int state, String incomingNumber) {
        if (state == TelephonyManager.CALL_STATE_RINGING) {
            if (qInProgress) {
                if (qSource.equals(Loading.TYPE_FUN) || (qResumable)) {
                    //Allow to Resume
                } else {
                    //Break and send abort
                    sendAbort();
                }
            }

        }
      }
   }

I am using LeakCanary lib to check memory leak and i am getting a memory leak of 6.1Mb from my activity.

Memory Leak

sendAbort() is the method in my activity which does few operations.

Can someone guide me how to take care of this issue? I am struggling with memory management.

1

There are 1 answers

0
Udit Shah On

I found a solution which stopped creating memory leak.

private static PhoneStateListener phoneStateListener=new PhoneStateListener(){

    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        if (state == TelephonyManager.CALL_STATE_RINGING) {
            if (st_qScreen.qInProgress) {
                if (st_qScreen.qSource.equals(Loading.TYPE_FUN) || (st_qScreen.qResumable)) {
                    //Allow to Resume
                } else {
                    //Break and send abort
                    st_qScreen.sendAbortQ();
                }
            }

        }
    }
};

Here st_qScreen is an instance of the current class.

@Override
protected void onResume() {
    super.onResume();
     tmgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
     tmgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}


@Override
protected void onPause() {
    super.onPause();
    tmgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
    tmgr=null;
}

I set phoneStateListener to null in onDestroy method.

For me this is not creating memory leaks anymore.