PhoneNumberUtilWrapper.java

 1package eu.siacs.conversations.utils;
 2
 3import android.content.Context;
 4import android.telephony.TelephonyManager;
 5
 6import java.util.Locale;
 7
 8import io.michaelrocks.libphonenumber.android.PhoneNumberUtil;
 9
10public class PhoneNumberUtilWrapper {
11
12    private static volatile PhoneNumberUtil instance;
13
14
15    public static String getCountryForCode(String code) {
16        Locale locale = new Locale("", code);
17        return locale.getDisplayCountry();
18    }
19
20    public static String getUserCountry(Context context) {
21        try {
22            final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
23            final String simCountry = tm.getSimCountryIso();
24            if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
25                return simCountry.toUpperCase(Locale.US);
26            } else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
27                String networkCountry = tm.getNetworkCountryIso();
28                if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
29                    return networkCountry.toUpperCase(Locale.US);
30                }
31            }
32        } catch (Exception e) {
33            // fallthrough
34        }
35        Locale locale = Locale.getDefault();
36        return locale.getCountry();
37    }
38
39    public static PhoneNumberUtil getInstance(final Context context) {
40        PhoneNumberUtil localInstance = instance;
41        if (localInstance == null) {
42            synchronized (PhoneNumberUtilWrapper.class){
43                localInstance = instance;
44                if (localInstance == null) {
45                    instance = localInstance = PhoneNumberUtil.createInstance(context);
46                }
47
48            }
49        }
50        return localInstance;
51    }
52
53}