How to know when a device is ringing in Android?

Saidel López
2 min readJan 13, 2020

Maybe a very basic question but I implemented a quick way to catch when the user’s device is ringing. This solution includes Broadcasts and TelephonyManager’s states.

Here’s the code…

To allow us to read the device’s state, in your AndroidManifestFile.xml add this in the permissions section.

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Add a new class in your project that extends BroadcastReceiver class. Implement the method onReceive() and subscribe to any changes to the phone state from TelephonyManager class

import android.content.BroadcastReceiver 
import android.content.Context
import android.content.Intent
import android.telephony.TelephonyManager
class IncomingCallBroadcastReceiver : BroadcastReceiver { override fun onReceive(context: Context, intent:Intent) {
val state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
state?.let { state ->
if(state == TelephonyManager.EXTRA_STATE_RINGING) {
val incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
startMyService(context, incomingNumber)
}
}
}
}

The method startMyService(context, incomingNumber) must start a new Service and handle the incoming phone number in the background. Also notice that EXTRA_STATE_RINGING is the value that TelephonyManager broadcasts to let other apps that the device is ringing. You can also access to the call information such as the incoming number via intent bundle and the name TelephonyManager.EXTRA_INCOMING_NUMBER

And finally, coming back to your AndroidManifest.xml, add your newly created class as a broadcast receiver

<receiver android:name="IncomingCallBroadcastReceiver"> 
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>

Warning

Whatever you want to do inside of the onChange method must be a Service or any Thread running in background. Why? Basically your app is messing with a call so Android OS will set your app a lowest priority, which means, if the process takes more than 5 seconds to run it will send the ANR warning message.

Also, never open an Activity from the onChange method. The user is receiving a call so your app may block the user to pickup the call.

To know more

Here’s the TelephonyManager documentation. You can find other interesting methods you may want to try on. Also the documentation to BroadcastReceiver so you can learn better the structure of broadcasting.

--

--