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

我需要以编程方式使用GPS获取当前位置。 我怎样才能实现它?


我已经用逐步描述创建了一个小应用程序来获取当前位置的GPS坐标。

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


看看它怎么运作:

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

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
  • 然后像这样创建一个LocationManager实例:

    LocationManager locationManager = (LocationManager)
    getSystemService(Context.LOCATION_SERVICE);
    
  • 检查GPS是否启用。

  • 然后实现LocationListener并获取坐标:

    LocationListener locationListener = new MyLocationListener();
    locationManager.requestLocationUpdates(
    LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
    
  • 以下是示例代码


  • /*---------- 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 + "n" + latitude + "nnMy 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) {}
    }
    


    以下是其他答案的其他信息。

    自Android以来

    GPS_PROVIDER and NETWORK_PROVIDER
    

    您可以注册到两者并同时从两个onLocationChanged(Location location)开始从onLocationChanged(Location location)获取事件。 到现在为止还挺好。 现在的问题是我们需要两个结果还是应该采取最好的。 因为我知道GPS_PROVIDER结果比NETWORK_PROVIDER有更好的准确性。

    我们来定义Location字段:

    private Location currentBestLocation = null;
    

    在我们开始收听位置更改之前,我们将实施以下方法。 该方法返回GPS和网络之间的最后一个已知位置。 对于这种方法,最好是新的。

    /**
     * @return the last know best location
     */
    private Location getLastBestLocation() {
        Location locationGPS = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        Location locationNet = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    
        long GPSLocationTime = 0;
        if (null != locationGPS) { GPSLocationTime = locationGPS.getTime(); }
    
        long NetLocationTime = 0;
    
        if (null != locationNet) {
            NetLocationTime = locationNet.getTime();
        }
    
        if ( 0 < GPSLocationTime - NetLocationTime ) {
            return locationGPS;
        }
        else {
            return locationNet;
        }
    }
    

    每当我们检索一个新位置时,我们都会将它与我们以前的结果进行比较。

    ...
    static final int TWO_MINUTES = 1000 * 60 * 2;
    ...
    

    我为onLocationChanged添加了一个新方法:

    @override
    public void onLocationChanged(Location location) {
    
        makeUseOfNewLocation(location);
    
        if(currentBestLocation == null){
            currentBestLocation = location;
        }
    
        ....
    }
    
    
    /**
     * This method modify the last know good location according to the arguments.
     *
     * @param location The possible new location.
     */
    void makeUseOfNewLocation(Location location) {
        if ( isBetterLocation(location, currentBestLocation) ) {
            currentBestLocation = location;
        }
    }
    
    ....
    
    /** Determines whether one location reading is better than the current location fix
     * @param location  The new location that you want to evaluate
     * @param currentBestLocation  The current location fix, to which you want to compare the new one.
     */
    protected boolean isBetterLocation(Location location, Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return true;
        }
    
        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
        boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
        boolean isNewer = timeDelta > 0;
    
        // If it's been more than two minutes since the current location, use the new location,
        // because the user has likely moved.
        if (isSignificantlyNewer) {
            return true;
            // If the new location is more than two minutes older, it must be worse.
        } else if (isSignificantlyOlder) {
            return false;
        }
    
        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;
    
        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(),
                                                    currentBestLocation.getProvider());
    
        // Determine location quality using a combination of timeliness and accuracy
        if (isMoreAccurate) {
            return true;
        } else if (isNewer && !isLessAccurate) {
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
            return true;
        }
        return false;
    }
    
    /** Checks whether two providers are the same */
    private boolean isSameProvider(String provider1, String provider2) {
        if (provider1 == null) {
            return provider2 == null;
        }
        return provider1.equals(provider2);
    }
    
    ....
    

    您可以通过GPS_PROVIDER or NETWORK_PROVIDER找到位置。

    Android中的位置服务概述。

    以下是一个尝试使用GPS查找位置的示例。 如果您的GPS不可用,请尝试使用网络查找位置。

    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;
        }
    }
    

    活动-AndroidGPSTrackingActivity.java

        public class AndroidGPSTrackingActivity extends Activity {
    
        Button btnShowLocation;
    
        // GPSTracker class
        GPSTracker gps;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
    
            // Show location button click event
            btnShowLocation.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View arg0) {
                    // Create class object
                    gps = new GPSTracker(AndroidGPSTrackingActivity.this);
    
                    // Check if GPS enabled
                    if(gps.canGetLocation()) {
    
                        double latitude = gps.getLatitude();
                        double longitude = gps.getLongitude();
    
                        // n is for new line
                        Toast.makeText(getApplicationContext(), "Your Location is - nLat: " + latitude + "nLong: " + longitude, Toast.LENGTH_LONG).show();
                    } else {
                        // Can't get location.
                        // GPS or network is not enabled.
                        // Ask user to enable GPS/network in settings.
                        gps.showSettingsAlert();
                    }
                }
            });
        }
    }
    

    Layout- main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
    
        <Button android:id="@+id/btnShowLocation"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Show Location"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"/>
    </RelativeLayout>
    

    AndroidManifest.xml中

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    
    链接地址: http://www.djcxy.com/p/16105.html

    上一篇: How do I get the current GPS location programmatically in Android?

    下一篇: Get screen dimensions in pixels