@@ -4,6 +4,8 @@ import android.content.Context;
import android.telephony.TelephonyManager;
import android.util.Log;
+import androidx.core.content.ContextCompat;
+
import org.osmdroid.util.GeoPoint;
import java.io.BufferedReader;
@@ -16,11 +18,14 @@ import eu.siacs.conversations.R;
public class LocationProvider {
- public static final GeoPoint FALLBACK = new GeoPoint(0.0,0.0);
+ public static final GeoPoint FALLBACK = new GeoPoint(0.0, 0.0);
- public static String getUserCountry(Context context) {
+ public static String getUserCountry(final Context context) {
try {
- final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
+ final TelephonyManager tm = ContextCompat.getSystemService(context, TelephonyManager.class);
+ if (tm == null) {
+ return getUserCountryFallback();
+ }
final String simCountry = tm.getSimCountryIso();
if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
return simCountry.toUpperCase(Locale.US);
@@ -30,40 +35,41 @@ public class LocationProvider {
return networkCountry.toUpperCase(Locale.US);
}
}
- } catch (Exception e) {
- // fallthrough
+ return getUserCountryFallback();
+ } catch (final Exception e) {
+ return getUserCountryFallback();
}
- Locale locale = Locale.getDefault();
+ }
+
+ private static String getUserCountryFallback() {
+ final Locale locale = Locale.getDefault();
return locale.getCountry();
}
- public static GeoPoint getGeoPoint(Context context) {
+ public static GeoPoint getGeoPoint(final Context context) {
return getGeoPoint(context, getUserCountry(context));
}
- public static synchronized GeoPoint getGeoPoint(Context context, String country) {
- try {
- BufferedReader reader = new BufferedReader(new InputStreamReader(context.getResources().openRawResource(R.raw.countries)));
+ public static synchronized GeoPoint getGeoPoint(final Context context, final String country) {
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(context.getResources().openRawResource(R.raw.countries)))) {
String line;
- while((line = reader.readLine()) != null) {
- String[] parts = line.split("\\s+",4);
+ while ((line = reader.readLine()) != null) {
+ final String[] parts = line.split("\\s+", 4);
if (parts.length == 4) {
if (country.equalsIgnoreCase(parts[0])) {
try {
return new GeoPoint(Double.parseDouble(parts[1]), Double.parseDouble(parts[2]));
- } catch (NumberFormatException e) {
+ } catch (final NumberFormatException e) {
return FALLBACK;
}
}
- } else {
- Log.d(Config.LOGTAG,"unable to parse line="+line);
}
}
- } catch (IOException e) {
- Log.d(Config.LOGTAG,e.getMessage());
+ } catch (final IOException e) {
+ Log.d(Config.LOGTAG, "unable to parse country->geo map", e);
}
return FALLBACK;
}
-}
+}