Gdzie ja jestem? - Get country
Komórka z Androidem rzeczywiście dobrze wie, gdzie to jest - ale czy istnieje sposób na odzyskanie kraju za pomocą czegoś w rodzaju kodu kraju?
Nie trzeba znać dokładnej pozycji GPS-kraj jest wystarczający
Po raz pierwszy pomyślałem o użyciu strefy czasowej, ale w rzeczywistości potrzebuję więcej informacji niż to, ponieważ to robi różnicę, jeśli lokalizacja jest Nowy Jork lub Lima.
tło pytania: mam aplikację, która wykorzystuje wartości temperatury i chciałbym ustawić domyślną jednostkę na Celsjusza lub Fahrenheita, w zależności od tego, czy lokalizacja jest nas, czy na zewnątrz
10 answers
Otrzymamy kod kraju :
String locale = context.getResources().getConfiguration().locale.getCountry();
Może również zastąpić getCountry () getISO3Country(), Aby uzyskać 3-literowy kod ISO dla danego kraju. Otrzymamy nazwę kraju :
String locale = context.getResources().getConfiguration().locale.getDisplayCountry();
Wydaje się to łatwiejsze niż inne metody i polega na ustawieniach lokalizacji w telefonie, więc jeśli użytkownik z USA jest za granicą, prawdopodobnie nadal chce Fahrenheita i to zadziała:) {]}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-07 15:47:35
/**
* 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) { }
return null;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-16 22:48:47
Właśnie się dowiedziałem, że jest jeszcze jeden sposób na uzyskanie kodu kraju, używając metody getSimCountryIso () TelephoneManager
:
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();
Ponieważ jest to kod sim, nie powinien się on również zmieniać podczas podróży do innych krajów.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-07 16:23:05
Użyj tego linku http://ip-api.com/json , to dostarczy wszystkie informacje jako json. Z tego json możesz łatwo dostać się do kraju. Ta strona działa przy użyciu bieżącego adresu IP, automatycznie wykrywa szczegóły IP i sendback.
Docs http://ip-api.com/docs/api:json mam nadzieję, że to pomoże.
Przykład json
{
"status": "success",
"country": "United States",
"countryCode": "US",
"region": "CA",
"regionName": "California",
"city": "San Francisco",
"zip": "94105",
"lat": "37.7898",
"lon": "-122.3942",
"timezone": "America/Los_Angeles",
"isp": "Wikimedia Foundation",
"org": "Wikimedia Foundation",
"as": "AS14907 Wikimedia US network",
"query": "208.80.152.201"
}
Uwaga: ponieważ jest to rozwiązanie innych firm, używaj tylko wtedy, gdy inne nie działają.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-25 11:19:48
Najpierw pobierz Menedżera lokalizacji. Następnie zadzwoń LocationManager.getLastKnownPosition
. Następnie utwórz Geokoder i wywołaj GeoCoder.getFromLocation
. Zrób to jest w osobnym wątku!! Spowoduje to wyświetlenie listy Address
obiektów. Zadzwoń i masz.
Pamiętaj, że ostatnia znana pozycja może być nieco Nieświeża, więc jeśli użytkownik właśnie przekroczył granicę, możesz nie wiedzieć o tym przez jakiś czas.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-04 11:34:13
You could use getNetworkCountryIso()
od TelephonyManager
Aby uzyskać kraj telefon jest obecnie w (choć najwyraźniej jest to zawodne w sieciach CDMA).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-31 22:46:03
Oto kompletne rozwiązanie oparte na LocationManager i jako alternatywa dla TelephonyManager i lokalizacji dostawcy sieci. Użyłem powyższej odpowiedzi od @ Marco W. do części awaryjnej (świetna odpowiedź jak sama w sobie!).
Uwaga: kod zawiera PreferencesManager, jest to klasa pomocnicza, która zapisuje i ładuje dane z SharedPrefrences. Używam go, aby uratować kraj do S " P, dostanę Kraj tylko wtedy, gdy jest pusty. Dla mojego produktu nie dbam o wszystkie krawędzie przypadki (użytkownik podróżuje za granicę i tak dalej).
public static String getCountry(Context context) {
String country = PreferencesManager.getInstance(context).getString(COUNTRY);
if (country != null) {
return country;
}
LocationManager locationManager = (LocationManager) PiplApp.getInstance().getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
else {
Geocoder gcd = new Geocoder(context, Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
if (addresses != null && !addresses.isEmpty()) {
country = addresses.get(0).getCountryName();
if (country != null) {
PreferencesManager.getInstance(context).putString(COUNTRY, country);
return country;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
country = getCountryBasedOnSimCardOrNetwork(context);
if (country != null) {
PreferencesManager.getInstance(context).putString(COUNTRY, country);
return country;
}
return null;
}
/**
* 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
*/
private static String getCountryBasedOnSimCardOrNetwork(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) {
}
return null;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-18 13:05:14
Używając GPS z szerokością i długością geograficzną, możemy uzyskać kod kraju.
Jeśli używamy telefonii, nie będzie działać, jeśli nie używamy karty sim i w locale, w oparciu o język, pokazuje kod kraju w niewłaściwy sposób.
Główna aktywność.java:
GPSTracker gpsTrack;
public static double latitude = 0;
public static double longitude = 0;
gpsTrack = new GPSTracker(TabHomeActivity.this);
if (gpsTrack.canGetLocation()) {
latitude = gpsParty.getLatitude();
longitude = gpsParty.getLongitude();
Log.e("GPSLat", "" + latitude);
Log.e("GPSLong", "" + longitude);
} else {
gpsTrack.showSettingsAlert();
Log.e("ShowAlert", "ShowAlert");
}
countryCode = getAddress(TabHomeActivity.this, latitude, longitude);
Log.e("countryCode", ""+countryCode);
public String getAddress(Context ctx, double latitude, double longitude) {
String region_code = null;
try {
Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
region_code = address.getCountryCode();
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return region_code;
}
GPSTracker.java:
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
mContext.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Log:
E / countryCode: IN
Edit: Use Fused Location Provider to get latitude and longitude update for better wynik.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-07 07:34:35
String locale = context.getResources().getConfiguration().locale.getCountry();
Jest przestarzały. Użyj tego zamiast:
Locale locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
locale = context.getResources().getConfiguration().getLocales().get(0);
} else {
locale = context.getResources().getConfiguration().locale;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-21 21:51:51
Użyłem GEOIP db i stworzyłem funkcję. Możesz użyć tego linku bezpośrednio http://jamhubsoftware.com/geoip/getcountry.php
{"country":["India"],"isoCode":["IN"],"names":[{"de":"Indien","en":"India","es":"India","fr":"Inde","ja":"\u30a4\u30f3\u30c9","pt-BR":"\u00cdndia","ru":"\u0418\u043d\u0434\u0438\u044f","zh-CN":"\u5370\u5ea6"}]}
Możesz pobrać autoload.php i .plik mmdb z https://dev.maxmind.com/geoip/geoip2/geolite2 /
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ip_address = $_SERVER['REMOTE_ADDR'];
//$ip_address = '3.255.255.255';
require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;
// This creates the Reader object, which should be reused across
// lookups.
$reader = new Reader('/var/www/html/geoip/GeoLite2-City.mmdb');
// Replace "city" with the appropriate method for your database, e.g.,
// "country".
$record = $reader->city($ip_address);
//print($record->country->isoCode . "\n"); // 'US'
//print($record->country->name . "\n"); // 'United States'
$rows['country'][] = $record->country->name;
$rows['isoCode'][] = $record->country->isoCode;
$rows['names'][] = $record->country->names;
print json_encode($rows);
//print($record->country->names['zh-CN'] . "\n"); // '美国'
//
//print($record->mostSpecificSubdivision->name . "\n"); // 'Minnesota'
//print($record->mostSpecificSubdivision->isoCode . "\n"); // 'MN'
//
//print($record->city->name . "\n"); // 'Minneapolis'
//
//print($record->postal->code . "\n"); // '55455'
//
//print($record->location->latitude . "\n"); // 44.9733
//print($record->location->longitude . "\n"); // -93.2323
?>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-04 07:07:34