且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Android 中以编程方式获取当前 GPS 位置?

更新时间:2023-01-27 14:43:35

我已经创建了一个带有分步说明的小应用程序来获取当前位置的 GPS 坐标.

I have created a small application with step by step description to get current location's GPS coordinates.

完整的示例源代码在获取当前位置坐标、城市名称 - 在 Android 中.

Complete example source code is in Get Current Location coordinates , City name - in Android.

看看它是如何工作的:

  • 我们需要做的就是在清单文件中添加这个权限:

  • All we need to do is add this permission in the manifest file:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

  • 然后像这样创建一个 LocationManager 实例:

  • And create a LocationManager instance like this:

    LocationManager locationManager = (LocationManager)
    getSystemService(Context.LOCATION_SERVICE);
    

  • 检查 GPS 是否启用.

  • Check if GPS is enabled or not.

    然后实现LocationListener并获取坐标:

    And then implement LocationListener and get coordinates:

    LocationListener locationListener = new MyLocationListener();
    locationManager.requestLocationUpdates(
    LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
    

  • 这是执行此操作的示例代码

  • Here is the sample code to do so

    /*---------- Listener class to get coordinates ------------- */
    private class MyLocationListener implements LocationListener {
    
        @Override
        public void onLocationChanged(Location loc) {
            editLocation.setText("");
            pb.setVisibility(View.INVISIBLE);
            Toast.makeText(
                    getBaseContext(),
                    "Location changed: Lat: " + loc.getLatitude() + " Lng: "
                        + loc.getLongitude(), Toast.LENGTH_SHORT).show();
            String longitude = "Longitude: " + loc.getLongitude();
            Log.v(TAG, longitude);
            String latitude = "Latitude: " + loc.getLatitude();
            Log.v(TAG, latitude);
    
            /*------- To get city name from coordinates -------- */
            String cityName = null;
            Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
            List<Address> addresses;
            try {
                addresses = gcd.getFromLocation(loc.getLatitude(),
                        loc.getLongitude(), 1);
                if (addresses.size() > 0) {
                    System.out.println(addresses.get(0).getLocality());
                    cityName = addresses.get(0).getLocality();
                }
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            String s = longitude + "
    " + latitude + "
    
    My Current City is: "
                + cityName;
            editLocation.setText(s);
        }
    
        @Override
        public void onProviderDisabled(String provider) {}
    
        @Override
        public void onProviderEnabled(String provider) {}
    
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    }