androidkotlinandroid-audiomanagerphone-state-listener

How to add two classes in supertype list, PhoneStateListener and AppCompatActivity


Is it possible to add PhoneStateListener() with AppCompatActivity()? The idea is to create a Phone Call Listener class similar to class CallListener : AppCompatActivity(), PhoneStateListener() {}. This errors with "Only one class may appear in a supertype list". I need AppCompatActivity because I need to use an AudioManager and the only way I know how to do that is with getSystemService() which isn't availble without AppCompatActivity. I also need the PhoneStateListener to know which state outbound calls are in. What is the correct way to set this up in Kotlin?


Solution

  • You can have a custom nested class or concrete class which extends PhoneStateListener.

    class CallListener:PhoneStateListener(){
        override fun onCellInfoChanged(cellInfo: MutableList<CellInfo>?) {
            super.onCellInfoChanged(cellInfo)
        }
    }
    

    if you need to access context inside this you probably need to pass it in constructor . But if you make it inner class CallListener the you can directly use Activity's reference. make sure you remove all resources of PhoneStateListener in onStopor onDestroy. Arrangement with inner class look somewhat like below .

     class MyActivity:AppCompatActivity(){
        lateinit var  telephonyManager :TelephonyManager
        lateinit var callListener: CallListener
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            telephonyManager = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
            callListener=CallListener()
            telephonyManager.listen(callListener),
        }
    
        inner class CallListener:PhoneStateListener(){
            override fun onCellInfoChanged(cellInfo: MutableList<CellInfo>?) {
                super.onCellInfoChanged(cellInfo)
            }
        }
    }