运行服务以获取位置详细信息

时间:2011-03-03 10:43:40

标签: android

在我的应用中,我需要创建一个Android服务来定期获取移动用户的当前位置(经度和纬度)。该服务应该每5分钟获取一次用户的位置..我怎样才能在后台运行的android服务中执行此操作。这是正确的方法吗?

3 个答案:

答案 0 :(得分:0)

您可以编写实现locationListener的私有/内部类(在您的服务中),并且在您的服务的onStart meethod中,您可以requestLocationUpdates将由您的侦听器监听

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
MyLocationListener listener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, listener);

答案 1 :(得分:0)

 LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);   
      LocationListener mlocListener = new MyLocationListener();
      mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
}
 public class MyLocationListener implements LocationListener
    {


        @Override
        public void onLocationChanged(Location loc)
        {
            Log.i("**************************************", "Location changed");

            loc.getLatitude();
            loc.getLongitude(); 
            String Text = "My current location is: " +"Latitude = " + loc.getLatitude() + "Longitude = " + loc.getLongitude();             
            Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onProviderDisabled(String provider)
        {
            Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
        }

        @Override
        public void onProviderEnabled(String provider)
        {
            Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras)
        {
        }

    }

答案 2 :(得分:0)

您无需服务即可完成此操作。为了在应用程序中每5分钟获取一次位置,您可以在活动上实现位置监听器。在设置位置管理器时,您可以指定minTime = 5mins (300000 ms)onlocationChanged方法将每隔5分钟调用一次,或者距离change > minDistance时调用,该方法首先出现。

LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
MyLocationListener listener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 300000, minDistance, listener);