Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting incoming and outgoing calls in android API29+

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.

like image 421
FarshidABZ Avatar asked Jun 30 '20 08:06

FarshidABZ


2 Answers

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) {
        ...
    }
}
like image 167
marmor Avatar answered Sep 30 '22 15:09

marmor


@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.

like image 38
FarshidABZ Avatar answered Sep 30 '22 15:09

FarshidABZ