Skip to content

Instantly share code, notes, and snippets.

@martarodriguezm
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martarodriguezm/b33c047184f1cae61b1a to your computer and use it in GitHub Desktop.
Save martarodriguezm/b33c047184f1cae61b1a to your computer and use it in GitHub Desktop.
Helper created for European Union regulation about cookies. It checks if android device is from one of the European Union countries to show the corresponding message.
import android.content.Context;
import android.telephony.TelephonyManager;
import android.util.Log;
import java.util.Arrays;
import java.util.Locale;
/**
* Created by marta on 29/7/15.
*/
public class CountryHelper {
private static final String TAG = CountryHelper.class.getSimpleName();
//European countries ISO 3166-1 alpha-2 country codes
private static final String[] COUNTRIES = {"at", "be", "bg", "hr", "cy", "cz", "dk", "fr", "de", "gr", "hu", "ie", "it", "lv", "lt", "lu", "mt", "nl", "pl", "pt", "ro", "sk", "si", "es", "se", "gb"};
/**
* Get ISO 3166-1 alpha-2 country code for this device (or null if not available)
* @param context Context reference to get the TelephonyManager instance from
* @return country code or null
*/
public static String getUserCountry(Context context) {
try {
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
final String simCountry = tm.getSimCountryIso();
if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
return simCountry.toLowerCase(Locale.US);
} else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
String networkCountry = tm.getNetworkCountryIso();
if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
return networkCountry.toLowerCase(Locale.US);
}
}
} catch (Exception e) {
Log.e(TAG, "Cannot get user country");
}
return "";
}
/**
* Checks if the device country if from the European Union
* @param context
* @return true if the device country is from the European Union false otherwise
*/
public static boolean isEuropeanCountry(Context context) {
String country = CountryHelper.getUserCountry(context);
Log.e(TAG, "country = " + country);
return Arrays.asList(COUNTRIES).contains(country);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment