An overview,

In the project, the longitude, latitude and city of the user’s location should be obtained and sent to the risk control system. Generally speaking, there are two ways to locate:

  1. Use third-party SDK to locate, such as Baidu Map, Autonavi Map, Google Map;
  2. Using the API in the Android native SDK;

This article describes the second way of locating — using the API in Android’s native SDK. If your project is more demanding, you are advised to use a third-party map library.

2. API positioning in Android native SDK

Android native access to the latitude and longitude of the two positioning methods: GPS positioning and Wifi positioning

  • GPS positioning is more accurate than Wifi positioning and can be used when there is no network, but it can not be used in the indoor basic sudden death.
  • WiFi location has no indoor or outdoor restrictions, and does not need to turn on GPS but requires networking. However, the test found that the onLocationChanged function (used to listen for latitude and longitude changes) cannot be triggered less than 30 seconds after WiFi location.

The example code is as follows:

public class TestLocationActivity extends AppCompatActivity {

    public static final int LOCATION_CODE = 301;
    private LocationManager locationManager;
    private String locationProvider = null;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLocation();
    }

    private void getLocationLocationManager = (locationManager) getSystemService(context.location_service); / / 2. Access to location providers, GPS NetWork or a List < String > will = locationManager. GetProviders (true);

        if(providers. Contains (locationManager.gps_provider)) {// If GPS locationProvider = locationManager.gps_provider; Log.v("TAG"."Positioning mode GPS");
        } else if(providers. Contains (LocationManager.NETWORK_PROVIDER)) {// If Network locationProvider = LocationManager.NETWORK_PROVIDER; Log.v("TAG"."Location mode Network");
        }else {
            Toast.makeText(this, "No location provider available", Toast.LENGTH_SHORT).show();
            return;
        }

        if(build.version.sdk_int >= build.version_codes.m) {// Obtain the permission (if the permission is not enabled, a dialog box will be displayed asking whether to enable the permission)if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ! = PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) ! = PackageManager. PERMISSION_GRANTED) {/ / request permissions ActivityCompat. RequestPermissions (this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE); }else{/ / 3. Access to the Location of the last time, generally the first run, this value is null Location Location = locationManager. GetLastKnownLocation (locationProvider);if(location! =null){ Toast.makeText(this, location.getLongitude() +"" + 
                                         location.getLatitude() + "",Toast.LENGTH_SHORT).show();
                    Log.v("TAG"."Get last location - latitude and longitude:"+location.getLongitude()+""+location.getLatitude());
                    getAddress(location);

                }else{// monitor geographical changes, The second and the third parameter respectively update minTime the shortest time and the shortest distance minDistace locationManager. RequestLocationUpdates (locationProvider, 3000, 1,locationListener); }}}else {
            Location location = locationManager.getLastKnownLocation(locationProvider);
            if(location! =null){ Toast.makeText(this, location.getLongitude() +"" + 
                                     location.getLatitude() + "", Toast.LENGTH_SHORT).show();
                Log.v("TAG"."Get last location - latitude and longitude:"+location.getLongitude()+""+location.getLatitude());
                getAddress(location);

            }else{// monitor geographical changes, The second and the third parameter respectively update minTime the shortest time and the shortest distance minDistace locationManager. RequestLocationUpdates (locationProvider, 3000, 1,locationListener); } } } public LocationListener locationListener = newLocationListener@override public void onStatusChanged(String Provider, int status, String Provider, int Status, String Provider, int Status, Bundle extras) {} // Provider is enabledenable@override public void onProviderEnabled(String Provider) {} // Provider is enableddisable@override public void onProviderDisabled(String Provider) {} public void onProviderDisabled(String Provider) {} @override public void onLocationChanged(Location Location) {if(location ! = null) {/ / if the location changes, to display location latitude and longitude Toast. The makeText (TestLocationActivity. This location. GetLongitude () +"" + 
                                                          location.getLatitude() + "", Toast.LENGTH_SHORT).show();
                Log.v("TAG"."Monitoring geographical position changes - Latitude and Longitude:"+location.getLongitude()+""+location.getLatitude()); }}}; @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) {case LOCATION_CODE:
                if(grantResults.length > 0 && grantResults[0] == getPackageManager().PERMISSION_GRANTED
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "Apply for permission", Toast.LENGTH_LONG).show();
                    try {
                        List<String> providers = locationManager.getProviders(true);
                        if(providers. Contains (LocationManager.NETWORK_PROVIDER)) {// If Network locationProvider = LocationManager.NETWORK_PROVIDER; }else if(providers. Contains (locationManager.gps_provider)) {// If GPS locationProvider = locationManager.gps_provider; } Location location = locationManager.getLastKnownLocation(locationProvider);if(location! =null){ Toast.makeText(this, location.getLongitude() +"" + 
                                                 location.getLatitude() + "", Toast.LENGTH_SHORT).show();
                            Log.v("TAG"."Get last location - latitude and longitude:"+location.getLongitude()+""+location.getLatitude());
                        }else{// monitor geographical changes, The second and the third parameter respectively update minTime the shortest time and the shortest distance minDistace locationManager. RequestLocationUpdates (locationProvider, 0, 0,locationListener); } }catch (SecurityException e){ e.printStackTrace(); }}else {
                    Toast.makeText(this, "Lack of access.", Toast.LENGTH_LONG).show();
                    finish();
                }
                break; }} private List<Address> getAddress(Location Location) {List<Address> result = null; try {if(location ! = null) { Geocoder gc = new Geocoder(this, Locale.getDefault()); result = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 1); Toast.makeText(this,"Obtain address information:"+result.toString(), Toast.LENGTH_LONG).show();
                Log.v("TAG"."Obtain address information:"+result.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    protected void onDestroy() { super.onDestroy(); locationManager.removeUpdates(locationListener); }}Copy the code

Add permissions to androidManifest.xml

<! -- rough location permission --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission> <! -- precise location permission --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Copy the code

Third, summary

First, set the location service Settings to the following figure:

This may not get the latitude and longitude. Why only perform GPS and not network when both network and GPS are available? Maybe for accuracy reasons, but after walking the GPS into the listener, the onLocationChanged() method is not executed because I’m indoors and not moving, so if you can’t get the latitude and longitude, you need to switch the location service to use network location only or turn off the phone’s GPS so that it can get it.