第一步获取权限
Manifest . permission. READ_PHONE_STATE Manifest . permission. ANSWER_PHONE_CALLS Manifest . permission. READ_CALL_LOG Manifest . permission. READ_CONTACTS
第二步 注册监听
private var telephonyManager: TelephonyManager ? = null private var mPhoneStateListener: PhoneStateListener ? = null private fun lisPhone ( ) { telephonyManager = getSystemService ( Context . TELEPHONY_SERVICE ) as TelephonyManager mPhoneStateListener = object : PhoneStateListener ( ) { override fun onCallStateChanged ( state: Int , phoneNumber: String ? ) { super . onCallStateChanged ( state, phoneNumber) when ( state) { TelephonyManager . CALL_STATE_IDLE -> { Log . e ( "电话监听" , "onCallStateChanged: 挂断${phoneNumber}" ) } TelephonyManager . CALL_STATE_OFFHOOK -> { Log . i ( "电话监听" , "onCallStateChanged: 接听${phoneNumber}" ) } TelephonyManager . CALL_STATE_RINGING -> { Log . i ( "电话监听" , "onCallStateChanged: 响铃${phoneNumber}" ) } } } } telephonyManager! ! . listen ( mPhoneStateListener! ! , PhoneStateListener . LISTEN_CALL_STATE ) }
结尾 取消监听
private fun cancelPhoneStateListener ( ) { if ( telephonyManager != null && telephonyManager != null ) { telephonyManager! ! . listen ( mPhoneStateListener, PhoneStateListener . LISTEN_NONE ) ; } }