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