There are many questions about detecting incoming and outgoing calls in android, but all of them are old and also android deprecates the useful functions, and google play rejects my application because I'm using them.
For detecting outgoing calls I used:
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
and also listening to android.intent.action.NEW_OUTGOING_CALL
broadcast listener.
According to the google document(this) we should use CallRedirectionService
and CallScreeningService
. but these services work on API 29+.
So is there any way to detect Incoming and outgoing calls that don't deprecate and don't use sensitive permissions?
I want to close my socket connection if there are any calls and reopen it if not.
You need a BroadcastReceiver for ACTION_PHONE_STATE_CHANGED
This will call your received whenever the phone-state changes from idle,ringing,offhook so from the previous value and the new value you can detect if this is an incoming / outgoing call.
A required permission would be "android.permission.READ_PHONE_STATE"
But if you also want to receive the EXTRA_INCOMING_NUMBER
in that broadcast, you'll need another permission: "android.permission.READ_CALL_LOG"
here's the receiver definition for your manifest:
<receiver android:name="PhoneStateReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
And the code something like this:
public class PhoneStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
...
}
}
@marmor answer is correct, I just want to complete it.
for reading phone state first we should add the permission to the manifest:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
and in receiver class, we can get current state by reading intent like this:
intent.extras["state"]
the result of extras could be:
RINGING -> If your phone is ringing
OFFHOOK -> If you are talking with someone (Incoming or Outcoming call)
IDLE -> if call ended (Incoming or Outcoming call)
With PHONE_STATE
broadcast we don't need to use PROCESS_OUTGOING_CALLS
permission or deprecated NEW_OUTGOING_CALL
action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With