13

I use BroadcastReceiver to intercept incoming call on Android phone as below

tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
Bundle bundle = intent.getExtras();
String number = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);

In the "private number" case, I tested on two devices, it shows the number as -1 on HTC Wildfire and -2 on Galaxy S. I checked the android.telephony.PhoneNumberUtils but it could't help me.

Is there a function or a generic way to detect a private number on Android phone?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Bao Le
  • 16,643
  • 9
  • 65
  • 68

1 Answers1

13

You pretty much answered your own question. Private numbers are sent to the phone as -1 or -2. In my app I check for an integer value that is less than 0 and if it is, I treat it as a private number. This sounds like what you want to do as well.

I hope my thoughts are helpful.

Camille Sévigny
  • 5,104
  • 4
  • 38
  • 61
  • 1
    I'm not sure it works for all devices since I could not find any document about this. – Bao Le Aug 19 '11 at 02:15
  • I agree with you. I do not know if there are any devices out there that break this "less than zero" rule, but for now it seems to work for me. Since there is no documentation and Android devices are numerous in their implementation, I am going with this rule until I get an error report from a user. Not the best thing to do, but the only thing given the facts at this time. – Camille Sévigny Aug 19 '11 at 12:58
  • 2
    @BaoLe The reason why this works can be seen the android source of CallLog.java here is a link, http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.3_r1/android/provider/CallLog.java#269 calls which are restricted are assigned a constant, defined in com.android.internal.telephony.CallerInfo as -1 for Unknown, -2 for private and -3 for payphone number – Sojurn Feb 11 '14 at 06:04
  • Does anyone know if this behavior is still valid in android 4.4? – alice.harrison May 29 '14 at 22:18
  • 1
    This is not true in at least Android 5.1, in which it returned null (for private number). Also, in Android Developers site: "If the incoming caller is from an unknown number, the extra will be populated with an empty string.". No idea from which API that is though, because as I said, with me it returns null on the getString with a private number. So I guess it's a good idea to check for empty strings, null strings, and negative numbers to address all cases. – Edw590 Jun 07 '20 at 12:49