如何获得基于GPS位置或国家代码的货币符号



我已经实现了一个迷你项目,我需要根据位置显示货币符号。如果我在印度,如果美元符号应该显示卢比符号,我已经实现了,但它总是显示英镑符号

我代码:

LocationManager locationManager = (LocationManager) getSystemService(ListActivity.LOCATION_SERVICE);
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
    Geocoder code = new Geocoder(ListActivity.this);
    try {
        List<Address> addresses = code.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
        Address obj = addresses.get(0);
        String cc = Currency.getInstance(obj.getLocale()).getSymbol();
        Log.d("Currency Symbol : ", cc);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我需要显示各自国家的货币符号,并从GPS中获取国家,我搜索了很多,最后得出了下面的代码,它工作正常,所以我想分享这个代码,其他人不能浪费时间


这里你需要第一个国家代码,如IN,US从纬度经度我们得到完整的地址


请在运行代码之前检查清单文件中的GPS权限。下面是一些权限


需要GPSTracker.java文件代码创建GPSTracker java文件并编写以下代码。在这条红色的线里别担心,它不会影响什么

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;
                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 latitude/longitude 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/Wi-Fi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog.
     * On pressing the Settings button it will launch Settings Options.
     * */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");
        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
        // On pressing the Settings button.
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });
        // On pressing the cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        // Showing Alert Message
        alertDialog.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;
    }
}

这里是mainactivity.java类

public class MainActivity extends AppCompatActivity {
    public static SortedMap < Currency, Locale > currencyLocaleMap;
    TextView t;
    Geocoder geocoder;
    private static final Map < String, Locale > COUNTRY_TO_LOCALE_MAP = new HashMap < String, Locale > ();
    static {
        Locale[] locales = Locale.getAvailableLocales();
        for (Locale l: locales) {
            COUNTRY_TO_LOCALE_MAP.put(l.getCountry(), l);
        }
    }
    public static Locale getLocaleFromCountry(String country) {
        return COUNTRY_TO_LOCALE_MAP.get(country);
    }
    String Currencysymbol = "";
    @
    Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        t = (TextView) findViewById(R.id.text);
        GPSTracker gpsTracker = new GPSTracker(MainActivity.this);
        geocoder = new Geocoder(MainActivity.this, getLocaleFromCountry(""));
        double lat = gpsTracker.getLatitude();
        double lng = gpsTracker.getLongitude();
        Log.e("Lat long ", lng + "lat long check" + lat);

        currencyLocaleMap = new TreeMap < Currency, Locale > (new Comparator < Currency > () {
              public int compare(Currency c1, Currency c2) {
                  return c1.getCurrencyCode().compareTo(c2.getCurrencyCode());
              }
          });
          for (Locale locale: Locale.getAvailableLocales()) {
              try {
                  Currency currency = Currency.getInstance(locale);
                  currencyLocaleMap.put(currency, locale);
                  Log.d("locale utill", currency + " locale1 " + locale.getCountry());
              } catch (Exception e) {
                  Log.d("locale utill", "e" + e);
              }
          }

          try {
              List < Address > addresses = geocoder.getFromLocation(lat, lng, 2);
              Address obj = addresses.get(0);
              Currencysymbol = getCurrencyCode(obj.getCountryCode());
              Log.e("getCountryCode", "Exception address " + obj.getCountryCode());
              Log.e("Currencysymbol", "Exception address " + Currencysymbol);
          } catch (Exception e) {
              Log.e("Exception address", "Exception address" + e);
              // Log.e("Currencysymbol","Exception address"+Currencysymbol);
        }
        t.setText(Currencysymbol);
    }
    public String getCurrencyCode(String countryCode) {
        String s = "";
        for (Locale locale: Locale.getAvailableLocales()) {
            try {
                if (locale.getCountry().equals(countryCode)) {
                    Currency currency = Currency.getInstance(locale);
                    currencyLocaleMap.put(currency, locale);
                    Log.d("locale utill", currency + " locale1 " + locale.getCountry() + "s " + s);
                    s = getCurrencySymbol(currency + "");
                }
            } catch (Exception e) {
                Log.d("locale utill", "e" + e);
            }
        }
        return s;
    }
    public String getCurrencySymbol(String currencyCode) {
        Currency currency = Currency.getInstance(currencyCode);
        System.out.println(currencyCode + ":-" + currency.getSymbol(currencyLocaleMap.get(currency)));
        return currency.getSymbol(currencyLocaleMap.get(currency));
    }
  }

你可以使用这个来获取你的Location的区域设置

Locale locale= getResources().getConfiguration().locale;
Currency currency=Currency.getInstance(locale);
String symbol = currency.getSymbol();

reference : Getting Current Locale

最新更新