Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to check whether a given phone number is of a cell phone or not?

Background

It is possible to check if a given string represents a valid phone number, using this code, together with the PhoneNumberUtil library by Google (available here) :

public static boolean isValidNumber(final PhoneNumber phone) {
    if (phone == null)
        return false;
    final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
    return phoneNumberUtil.isValidNumber(phone);
}

public static boolean isValidPhoneNumber(String phone) {
    if (TextUtils.isEmpty(phone))
        return false;
    phone = phone.replaceAll("[^0-9]", "");
    final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
    PhoneNumber phoneNumber = null;
    try {
        phoneNumber = phoneNumberUtil.parse(phone, Locale.getDefault().getCountry());
    } catch (final Exception e) {
    }
    return isValidNumber(phoneNumber);
}

The problem

This is only a general check, but I can't find out if it's possible to know if the phone number is actually of a mobile device.

What I've tried

As I've read in some websites, the above check might need to have just a small adjustment to know if it's of a mobile device, but according to my tests, it's wrong :

    ...
    phone = phone.replaceAll("[^0-9]", "");
    if (phone.length() < 7)
        return false;
    ...

The question

Is it possible to know if the phone number is of a mobile device?

If so, how ?

like image 867
android developer Avatar asked Jan 17 '17 15:01

android developer


1 Answers

Seems I've missed the function in the library. Here's how to do it:

public static boolean isValidMobileNumber(String phone) {
    if (TextUtils.isEmpty(phone))
        return false;
    final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
    try {
        PhoneNumber phoneNumber = phoneNumberUtil.parse(phone, Locale.getDefault().getCountry());
        PhoneNumberUtil.PhoneNumberType phoneNumberType = phoneNumberUtil.getNumberType(phoneNumber);
        return phoneNumberType == PhoneNumberUtil.PhoneNumberType.MOBILE;
    } catch (final Exception e) {
    }
    return false;
}

EDIT: it seems some numbers (in the US and a few others ) cannot be determined whether they are of mobile phones or not. In this case, FIXED_LINE_OR_MOBILE is returned.

If you still need to know if the phone number is mobile, there are online services to check it out (though they can't know all, of course), such as Pathfinder.

like image 74
android developer Avatar answered Sep 25 '22 20:09

android developer