使用TelephonyManager监听通话事件的内存泄露

 
  
//使用TelephonyManager 对通话的监听
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                PhoneState phoneState = new PhoneState();
                telephonyManager.listen(phoneState, PhoneStateListener.LISTEN_CALL_STATE);
        //响铃
        protected void phoneRinging() {
        }

        //接通
        protected void phoneOffhook() {
        }

        //挂断
        protected void phoneIdle() {
        }

        private class PhoneState extends PhoneStateListener {
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {

                switch (state) {
                    case TelephonyManager.CALL_STATE_OFFHOOK:
                        phoneOffhook();
                        break;
                    case TelephonyManager.CALL_STATE_IDLE:
                        phoneIdle();
                        break;
                    case TelephonyManager.CALL_STATE_RINGING:
                        phoneRinging();
                        break;
                }

            }
        }
但是如果在Activity中执行这些代码,会导致内存泄露。重复进入Activity会导致OOM
所以在离开时可以执行
 
  
 private void unRegisterPhoneState(){
        if (phoneState!=null && telephonyManager!=null){
            telephonyManager.listen(phoneState,PhoneStateListener.LISTEN_NONE);
            phoneState = null;
            telephonyManager = null;
        }
    }
来释放资源,但是亲测过程中,在Android5.1以上的操作系统中,GC并不会立即回收Listen资源,具体我没有看为什么,所以我建议还是用Application的Context单例对上述情况进行操作。
 
  
笔者上次粗心犯下的错误,记录一下


你可能感兴趣的:(Android)