SoFunction
Updated on 2025-03-01

Simple examples of implementing GPS positioning in Android

I spent more than an hour today and wrote a small example of GPS obtaining geographical location code, including referring to some codes on the Internet and making some modifications to the code. I hope it will help you. The specific code is as follows: To use the GPS device on the Adnroid platform, you need to add permissions first, so you need to add the following permissions:

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

The specific implementation code is as follows:

First, determine whether the GPS module exists or is enabled:

private void openGPSSettings() {
    LocationManager alm = (LocationManager) this
        .getSystemService(Context.LOCATION_SERVICE);
    if (alm
        .isProviderEnabled(.GPS_PROVIDER)) {
      (this, "GPS module is normal", Toast.LENGTH_SHORT)
          .show();
      return;
    }

    (this, "Please enable GPS!", Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
    startActivityForResult(intent,0); //This is after the setting is completed, return to the acquisition interface
  }

If it is enabled normally, it will directly enter the display page. If it is enabled abnormally, it will go to the GPS settings page:

Get the code as follows:

private void getLocation()
  {
    // Obtain location management services    LocationManager locationManager;
    String serviceName = Context.LOCATION_SERVICE;
    locationManager = (LocationManager) (serviceName);
    // Find service information    Criteria criteria = new Criteria();
    (Criteria.ACCURACY_FINE); // High precision    (false);
    (false);
    (true);
    (Criteria.POWER_LOW); // Low power consumption
    String provider = (criteria, true); // Get GPS information    Location location = (provider); // Get location via GPS    updateToNewLocation(location);
    // Set the listener, the minimum time for automatic update is N seconds (1 second is 1*1000, so writing is mainly for convenience) or the minimum displacement change exceeds N meters    (provider, 100 * 1000, 500,
        locationListener);  }

You can get the geographical location information here, but it still needs to be displayed. Then use the following method to display it:

private void updateToNewLocation(Location location) {

    TextView tv1;
    tv1 = (TextView) (.tv1);
    if (location != null) {
      double latitude = ();
      double longitude= ();
      ("latitude:" + latitude+ "\nLongitude" + longitude);
    } else {
      ("Unable to obtain geographic information");
    }

  }

In this way, you can get the geographical location of the current user. At least how to implement it on the map will be obtained below and displayed! Thanks to the person who referenced the code!