简体   繁体   中英

Location tracking in background while onChanging of the location in Android

I am developing android application using the Location. I am able to get the current location using following code.

  public void GetLocation()
     {
        boolean isGPSEnabled = false;
        boolean isNetworkEnabled = false;
        private LocationManager mLocationManager;
        private String mProvider;
        mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();     
        isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if(isGPSEnabled && isNetworkEnabled)
        {
            mProvider = mLocationManager.getBestProvider(criteria, false);
            Location location = mLocationManager.getLastKnownLocation(mProvider);           
            Sring mLatitude=String.valueOf(arg.getLatitude());           
            String mLongitude=String.valueOf(arg.getLongitude());            
        }
    }

I need to update the location of the user in background, once the location is changed not frequently. How can I achieve this?

You need to use location listener. You can listen the location in specific meters or specific time interval. Check this tutorial.

locationManager.requestLocationUpdates(

                LocationManager.GPS_PROVIDER,

                **MINIMUM_TIME_BETWEEN_UPDATES**,

                **MINIMUM_DISTANCE_CHANGE_FOR_UPDATES**,

                new MyLocationListener()

        );
public class CurrentLatLng implements LocationListener {

    public static final int GPS_NOT_ENABLED = -1;
    public static final int VALID = 1;

    LocationManager manager;
    Context context;

    public CurrentLatLng(Context context) {
        this.context = context;
    }

    public void getCurrentLatLng() {

        //Check if GPS is enabled
        if (Commons.isGPSEnabled(context)) {
            manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10, 10, this);
        } else {
            // GPS NOT ENABLED. EVEN THEN THE LOCATION WILL BE RECIEVED AS WE ARE GETTING LOCATION BY NETWORK_PROVIDER
        }
    }

    @Override
    public void onLocationChanged(Location l) {
        // HERE YOU WILL GET THE LATEST LOCATION AND WILL BE UPDATING WHENEVER YOU CHANGE YOUR LOCATION. 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM