Google Maps Android API v2 creating a new LocationSource

后端 未结 3 656
执念已碎
执念已碎 2020-12-09 13:28

A LocationSource is defined in Google Maps Android API v2.

It is used for googlemap as the location provider. By default, the location source is provide

3条回答
  •  一生所求
    2020-12-09 13:50

    Here is a simple implementation of LocationSource interface. In my case I'm registering both GPS and Network location providers. As mentioned by @CommonsWare, implementation may very depending on your needs. I would suggest reading official documentation about Location service in order to better understand how to utilize your needs and save some battery power

    public class CurrentLocationProvider implements LocationSource, LocationListener
    {
        private OnLocationChangedListener listener;
        private LocationManager locationManager;
    
        public CurrentLocationProvider(Context context)
        {
            locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        }
    
        @Override
        public void activate(OnLocationChangedListener listener)
        {
            this.listener = listener;
            LocationProvider gpsProvider = locationManager.getProvider(LocationManager.GPS_PROVIDER);
            if(gpsProvider != null)
            {
                locationManager.requestLocationUpdates(gpsProvider.getName(), 0, 10, this);
            }
    
            LocationProvider networkProvider = locationManager.getProvider(LocationManager.NETWORK_PROVIDER);;
            if(networkProvider != null) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000 * 60 * 5, 0, this);
            }
        }
    
        @Override
        public void deactivate()
        {
            locationManager.removeUpdates(this);
        }
    
        @Override
        public void onLocationChanged(Location location)
        {
            if(listener != null)
            {
                listener.onLocationChanged(location);
            }
        }
    
        @Override
        public void onProviderDisabled(String provider)
        {
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public void onProviderEnabled(String provider)
        {
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras)
        {
            // TODO Auto-generated method stub
    
        }
    }
    

    And here is how I would use this class:

    protected void setUpMap() {
        //init routine
        .......
    
        this.map.setLocationSource(new CurrentLocationProvider(this));
        .......       
    }
    

    EDIT Please not that this solution is obsolete! You need to use FusedLocationProviderApi in conjunction with GoogleApiClient for tracking current location

提交回复
热议问题