LocationProvider.java

 1package eu.siacs.conversations.utils;
 2
 3import android.content.Context;
 4import android.telephony.TelephonyManager;
 5import android.util.Log;
 6
 7import androidx.core.content.ContextCompat;
 8
 9import org.osmdroid.util.GeoPoint;
10
11import java.io.BufferedReader;
12import java.io.IOException;
13import java.io.InputStreamReader;
14import java.util.Locale;
15
16import eu.siacs.conversations.Config;
17import eu.siacs.conversations.R;
18
19public class LocationProvider {
20
21    public static final GeoPoint FALLBACK = new GeoPoint(0.0, 0.0);
22
23    public static String getUserCountry(final Context context) {
24        try {
25            final TelephonyManager tm = ContextCompat.getSystemService(context, TelephonyManager.class);
26            if (tm == null) {
27                return getUserCountryFallback();
28            }
29            final String simCountry = tm.getSimCountryIso();
30            if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
31                return simCountry.toUpperCase(Locale.US);
32            } else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
33                String networkCountry = tm.getNetworkCountryIso();
34                if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
35                    return networkCountry.toUpperCase(Locale.US);
36                }
37            }
38            return getUserCountryFallback();
39        } catch (final Exception e) {
40            return getUserCountryFallback();
41        }
42    }
43
44    private static String getUserCountryFallback() {
45        final Locale locale = Locale.getDefault();
46        return locale.getCountry();
47    }
48
49    public static GeoPoint getGeoPoint(final Context context) {
50        return getGeoPoint(context, getUserCountry(context));
51    }
52
53
54    public static synchronized GeoPoint getGeoPoint(final Context context, final String country) {
55        try (BufferedReader reader = new BufferedReader(new InputStreamReader(context.getResources().openRawResource(R.raw.countries)))) {
56            String line;
57            while ((line = reader.readLine()) != null) {
58                final String[] parts = line.split("\\s+", 4);
59                if (parts.length == 4) {
60                    if (country.equalsIgnoreCase(parts[0])) {
61                        try {
62                            return new GeoPoint(Double.parseDouble(parts[1]), Double.parseDouble(parts[2]));
63                        } catch (final NumberFormatException e) {
64                            return FALLBACK;
65                        }
66                    }
67                }
68            }
69        } catch (final IOException e) {
70            Log.d(Config.LOGTAG, "unable to parse country->geo map", e);
71        }
72        return FALLBACK;
73    }
74
75}