Find Country code by using Mobile Number Android - android

Is there any way to find the country code from my mobile number. Basically, I am working for a chat application I need to find the country code by using the mobile number. Is it possible?
For example:
My Country - India,
Country Code - +91,
My number - 9787248566
Now I have only my number . I don't know the country code. I don't know which country it is. Is it possible to achieve this in Android programmatically?

If you already have complete mobile number in a specific format e.g. +91-99xxxxxxxx and want to fetch country code = IN, then here is a reference to a solution.
Use a lib in your gradle.
//Phone Utils lib.
implementation 'com.googlecode.libphonenumber:libphonenumber:7.0'
And the code which will help to find the country code and other information is as below.
PhoneNumberUtil utils = PhoneNumberUtil.getInstance();
try {
for (String region : utils.getSupportedRegions()) {
// Check whether it's a valid number.
boolean isValid = utils.isPossibleNumber(mobileNo, region);
if (isValid) {
Phonenumber.PhoneNumber number = util.parse(mobileNo, region);
// Check whether it's a valid number for the given region.
isValid = utils.isValidNumberForRegion(number, region);
if (isValid) {
Log.d("Region:" , region); // IN
Log.d("Phone Code", number.getCountryCode()); // 91
Log.d("Phone No.", number.getNationalNumber()); // 99xxxxxxxxxx
}
}
}
} catch (NumberParseException e) {
e.printStackTrace();
}

Use TelephonyManager.getSimCountryIso().
If you want to map that to the number, see how to get country phone prefix from iso

Related

How to match phone numbers from user's contact list if numbers are in different format?

I have a question about how to match phone numbers from user's contact list with phone numbers I have on remote database. Flow goes like this:
User registers on my app with his phone number (so does any other user)
App ask for contact permission
App sends contacts (phone numbers) to server to match against other registered numbers
The problem I have is that users register their phone number in format: +1XXXYYY.
For example person A registers with number +1222333. It might happen that person B has person A in his contact list as 0222333, how should I match that number? I can't know if prefix is "+1" or some other number.
I would like to recommend the libphonenumber library: https://github.com/google/libphonenumber
It can parse numbers and then output then to a standardized format. The official library has support for Java, C++ and JavaScript but there are also ports to other languages (see the bottom of the Github page)
Here is a quick example on how to format a national number as an international one in java
public static String getInternationalNumber(String localNumber, String regionCode) {
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber phoneNumber;
try {
phoneNumber = phoneUtil.parse(localNumber, regionCode);
}
catch (NumberParseException e) {
return null;
}
return (phoneUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL));
}
You can probably assume that the numbers in the user's contact list have the same country code as the user.
To find which country code your user's phone number has you can do something like this (assuming it is an international number)
public static String getRegionCode(String phone) {
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber phoneNumber;
try {
phoneNumber = phoneUtil.parse(phone, "");
}
catch (NumberParseException e) {
return null;
}
return phoneUtil.getRegionCodeForNumber(phoneNumber);
}

Fetch Merchant Name from Transaction SMS - Android

I want to fetch Merchant Name from Bank Transaction SMS. For this I used following regx;
Pattern.compile("(?i)(?:\\sat\\s|in\\*)([A-Za-z0-9]*\\s?-?\\s?[A-Za-z0-9]*\\s?-?\\.?)")
Its works fine with those SMS which contains at / in but what if SMS contains other than this two words.
For example, SMS is like ;
Dear Customer, You have made a Debit Card purchase of INR1,600.00 on
30 Jan. Info.VPS*AGGARWAL SH.
Then how to fetch AGGARWAL SH from above SMS?
You can use this below code to fetch Merchant Name from String
private void extractMerchantNameFromSMS(){
try{
String mMessage= "Dear Customer, You have made a Debit Card purchase of INR1,600.00 on 30 Jan. Info.VPS*AGGARWAL SH.";
Pattern regEx = Pattern.compile("(?i)(?:\\sInfo.\\s*)([A-Za-z0-9*]*\\s?-?\\s?[A-Za-z0-9*]*\\s?-?\\.?)");
// Find instance of pattern matches
Matcher m = regEx.matcher(mMessage);
if(m.find()){
String mMerchantName = m.group();
mMerchantName = mMerchantName.replaceAll("^\\s+|\\s+$", "");//trim from start and end
mMerchantName = mMerchantName.replace("Info.","");
FileLog.e(TAG, "MERCHANT NAME : "+mMerchantName);
}else{
FileLog.e(TAG, "MATCH NOTFOUND");
}
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}

How can I map a string and compare with another string?

This question might be silly but I'm not able to achieve this. I have a payment device that I'm connected via bluetooth to my app. For the device to display currency code, I need to pass a string, like this :
String codeForPaymendDevice = "978";
This "978" basically sends "EUR" currency code and displays on the screen of the payment device. (The device's library maps and handles this). In my app, when the user makes a purchase in EUR currency, it should compare with "978(EUR)" and if both matches, it should parse codeForPaymentDevice. I'm not able to do this because I cannot compare "EUR" with 978 (as my code doesn't know 978 is EUR, only the payment device knows 978 is EUR).
What I need to do is, map "978" to "EUR" code and then compare transaction.getCurrencyCode() with the mapped variable and then parse it.
private SaleRequest buildTransactionRequest(Transaction transaction) {
final SaleRequest tr = new SaleRequest();
BigDecimal amount = getAmountPaid();
String codeForPaymentDevice = "978";
String formattedAmount;
try {
if (!transaction.getCurrencyCode().equalsIgnoreCase(CREW_CURRENCY)) {
formattedAmount = AirFiApplication
.getPriceFormatter(AirFiApplication.getCurrency(transaction.getCurrencyCode())).format(amount);
// transaction.getCurrencyCode = EUR
tr.setCurrency(codeForPaymentDevice); // TODO remove hardcoding
}
} catch (MPosValueException e) {
LOG.error("Error while building transaction request due to {}", e.getLocalizedMessage());
}
return tr;
}
You can create a Map with some key (for now I have used currency code) with the value you need to pass as the value.
Map<String, String> map = new HashMap<>();
map.put("EUR", "978");
map.put("INR", "979");
map.put("USD", "980");
map.put("AED", "981");
...
In your code,
tr.setCurrency(map.get(transaction.getCurrencyCode()));

How To Know Country name from device ip address?

I can get the country name from a device using the location of the device's sim, but for a tablet without a sim this won't work. How can I get the country code or country name from the device's ip when it's connected to internet?
Here's a GeoIP library for Android you can use in your project.
It uses an online API to get the country from the IP address.
https://github.com/seventhmoon/GeoIp-android
Here's a snippet on how to use it:
ApiManager apiManager = new ApiManager(Volley.newRequestQueue(context));
apiManager.getGeoIpInfo(new Response.Listener<GeoIpResponseModel>() {
#Override
public void onResponse(GeoIpResponseModel response) {
//This is how you get the information.
//not all attribute are listed
String country = response.getCountry();
String city = response.getCity();
String countryCode = resopnse.getCountryCode();
double latitude = response.getLatitude();
double longtidue = response.getLongitude();
String region = response.getRegion();
String timezone = response.getTimezone();
String isp = response.getIsp();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String errorMessage = error.toString();
}
});
It depends on how exact you want to be - noting that this technique is not very accurate anyway! There are all sorts of ways of defeating geolocation by IP address.
However, there are websites that you can query with the IP address and it will return a country.
But if you don't want to go online to find out, you will need to take a dump of the current list, encode it in a lookup table, and store it inside your program.
You will not want to store every address - there are 4 billion possible ones - but instead store large ranges. This will reduce the table size considerably.

Android how to check mobile number

In Android We can save mobile number/landline number/etc..how To check that the number is mobile number?
while (phones.moveToNext())
{
int phoneType = phones.getInt(phones.getColumnIndex(Phone.TYPE));
if (phoneType == Phone.TYPE_MOBILE)
{
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
break;
}
}
with this code it fetches the mobile number of TYPE_MOBILE ..but what if the user put land line number in TYPE_MOBILE?
This is best way given inbuilt.
private boolean isValidMobile(String phone)
{
return android.util.Patterns.PHONE.matcher(phone).matches();
}
In android you will not get mobile number, if user save our own number in contact as owner then you will get. If you want user mobile number then you can use OTP verification related libraries and then you will got number

Categories

Resources