Get latitude and longitude in Android native mode

Get latitude and longitude in Android native mode
Two positioning methods: GPS positioning and WiFi Positioning
Advantages and disadvantages:

Third party map library is recommended if the project positioning requirements are high

GPS positioning is more accurate than Wifi Positioning and can be used without network, but it can't be used basically in the room.
There is no indoor and outdoor limit for WiFi Positioning and GPS is not needed to be turned on, but networking is needed. In addition, the test found that the trigger interval of onLocationChanged function (used to monitor the change of longitude and latitude) cannot be less than 30s during WiFi Positioning.
Below is the code of Wifi location

public class GPSActivity extends AppCompatActivity {

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

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

private void getLocation () {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    //Get all available location providers
    List<String> providers = locationManager.getProviders(true);
    if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
        //If it's Network
        locationProvider = LocationManager.NETWORK_PROVIDER;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        //Get permission (if you do not have permission to open, a dialog box will pop up asking whether to open 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 permission
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
        } else {
            //Monitoring geographic location changes
            locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);
            Location location = locationManager.getLastKnownLocation(locationProvider);
            if (location != null) {
                //Enter latitude and longitude
                Toast.makeText(this, location.getLongitude() + " " + location.getLatitude() + "", Toast.LENGTH_SHORT).show();
            }
        }
    } else {
        //Monitoring geographic location changes
        locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);
        Location location = locationManager.getLastKnownLocation(locationProvider);
        if (location != null) {
            //It is not empty and displays the longitude and latitude of geographical location.
            Toast.makeText(this, location.getLongitude() + " " + location.getLatitude() + "", Toast.LENGTH_SHORT).show();
        }
    }
}

public LocationListener locationListener = new LocationListener() {
    // The Provider's state triggers this function when the three states of available, temporarily unavailable and no service switch directly
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
    // Trigger this function when the Provider is enable d, for example, GPS is turned on
    @Override
    public void onProviderEnabled(String provider) {
    }
    // Trigger this function when the Provider is disable d, for example, GPS is turned off
    @Override
    public void onProviderDisabled(String provider) {
    }
    //This function is triggered when the coordinate changes. If the Provider passes in the same coordinate, it will not be triggered.
    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            //It is not empty and displays the longitude and latitude of geographical location.
            Toast.makeText(GPSActivity.this, location.getLongitude() + " " + location.getLatitude() + "", Toast.LENGTH_SHORT).show();
        }
    }
};

@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, "Application authority", Toast.LENGTH_LONG).show();
                try {
                    List<String> providers = locationManager.getProviders(true);
                    if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
                        //If it's Network
                        locationProvider = LocationManager.NETWORK_PROVIDER;
                    }else if (providers.contains(LocationManager.GPS_PROVIDER)) {
                        //If it's GPS
                        locationProvider = LocationManager.GPS_PROVIDER;
                    }
                    //Monitoring geographic location changes
                    locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);
                    Location location = locationManager.getLastKnownLocation(locationProvider);
                    if (location != null) {
                        //It is not empty and displays the longitude and latitude of geographical location.
                        Toast.makeText(GPSActivity.this, location.getLongitude() + " " + location.getLatitude() + "", Toast.LENGTH_SHORT).show();
                    }
                }catch (SecurityException e){
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(this, "Lack of authority", Toast.LENGTH_LONG).show();
                finish();
            }
            break;
    }
}

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

}
Don't forget to add permissions to Android manifest.xml

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

GPS positioning only needs to replace the following code

   if (providers.contains(LocationManager.GPS_PROVIDER)) {
        //If it's GPS
        locationProvider = LocationManager.GPS_PROVIDER;
    } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
        //If it's Network
        locationProvider = LocationManager.NETWORK_PROVIDER;
    } else {
        Intent i = new Intent();
        i.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(i);
    }

Author: dk123sw
Source: CSDN
Original text: https://blog.csdn.net/dk123sw/article/details/90410829
Copyright notice: This is the original article of the blogger. Please attach the link of the blog!

Tags: Android network less xml

Posted on Sat, 02 Nov 2019 12:16:44 -0700 by metrostars