我想听听当我的应用程序在前台时是否有电话。
以前是这样的,但现在不推荐使用 listen() :
val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
tm.listen(object : PhoneStateListener() {
override fun onCallStateChanged(state: Int, phoneNumber: String?) {
super.onCallStateChanged(state, phoneNumber)
when (state) {
TelephonyManager.CALL_STATE_RINGING -> transcribingAudioConsumer.stopTranscription(null)
else -> {}
}
}
}, PhoneStateListener.LISTEN_CALL_STATE)
我尝试过这样的事情,但我找不到正确的方法来实现它。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
tm.registerTelephonyCallback({ it.run() }, MyPhoneStateListener())
}
@RequiresApi(Build.VERSION_CODES.S)
class MyPhoneStateListener : TelephonyCallback(), TelephonyCallback.CallStateListener {
override fun onCallStateChanged(state: Int) {
when (state) {
TelephonyManager.CALL_STATE_RINGING -> {
Timber.e("omg RING")
}
TelephonyManager.CALL_STATE_OFFHOOK -> {
Timber.e("omg hook")
}
TelephonyManager.CALL_STATE_IDLE -> {
Timber.e("omg idle")
}
}
}
}