在Android中更改位置时在后台进行位置跟踪

时间:2013-10-04 05:50:24

标签: android location locationmanager locationlistener

我正在使用Location开发Android应用程序。我可以使用以下代码获取当前位置。

  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());            
        }
    }

我需要在不经常更改位置后,在后台更新用户的位置。我该如何实现?

2 个答案:

答案 0 :(得分:0)

您需要使用位置监听器。您可以在特定的米或特定时间间隔内收听位置。查看this tutorial.

locationManager.requestLocationUpdates(

                LocationManager.GPS_PROVIDER,

                **MINIMUM_TIME_BETWEEN_UPDATES**,

                **MINIMUM_DISTANCE_CHANGE_FOR_UPDATES**,

                new MyLocationListener()

        );

答案 1 :(得分:0)

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. 
    }
}