Location of Android Development

_The positioning written here is native, that is, the positioning function of the system itself.

_First, introduce how you can always get the location information, then introduce a location update separately.On systems 6.0 and above, run-time privileges are required to use positioning.

Always get location information

Method 1:

//Create a location listener
 LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            //Location Update

        public void onStatusChanged(String provider, int status, Bundle extras) {
            //Provider hardware state change will be invoked

        public void onProviderEnabled(String provider) {
            //Provider enablement will be invoked

        public void onProviderDisabled(String provider) {
            //Provider disable will be called
LocationManager locationManager = 
//Parameter 1: Location provider, where only gps is used
//Parameter 2: Location interval update time
//Parameter 3: Positioning interval distance    
//Events are triggered when the positioning interval update time or the positioning interval distance is exceeded.
//Parameter 4: Location listenerLocionManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1,0, locationListener;
//Cancel Location Service

Method 2:
_Get location information by being broadcast through pendingintent and receiving broadcast.

        Intent intent = new Intent(this, LocaReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 200
                , intent, PendingIntent.FLAG_UPDATE_CURRENT);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 0, pi);

_The type of broadcasting receiver to be statically registered.

public class LocaReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        //Getting location information
        Location location = (Location) intent.getExtras().get(LocationManager.KEY_LOCATION_CHANGED);
//Cancel Location Services

Single location update
It's great to use this if you just want to locate it.
Method 1:

//Parameter 1: Location Provider
//Parameter 2: Location listener
//Parameter three: set NULL
 locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,locationListener, null);

Method 2:

//Broadcast receiver is static, LocaReceiver code unchanged
 Intent intent = new Intent(this, LocaReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, pendingIntent);

_Don't forget permissions.

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

Tags: Android

Posted on Sun, 12 Jul 2020 11:58:09 -0400 by MinDFreeZ