应该在哪里捕获位置

时间:2014-03-10 00:49:24

标签: android locationmanager

正如你们许多人所知,请求位置更新的(默认?)方式是调用此代码:

LocationListener locationListener = new MyLocationListener();  
locationManager.requestLocationUpdates(  
LocationManager.GPS_PROVIDER, 5000, 10, locationListener);

现在,假设您必须接收位置更新或很长一段时间(即使应用程序处于后台)。这意味着:

  1. 无法将LocationListener“绑定”到活动,因为一旦活动被销毁,将不再捕获位置。
  2. 位置管理器不能绑定到IntentService,因为它会立即执行并完成。
  3. 我的问题:即使您的应用在后台,即使是长时间捕获位置更新的最佳位置也在哪里?

1 个答案:

答案 0 :(得分:0)

即使应用关闭,也会持续为位置更新提供服务

public class gpsservice extends Service{

    private LocationManager locationManager;
    MyLocationListener locationListenerp;
    public gpsservice() {


    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void onCreate() {

        locationManager = (LocationManager) 
                getSystemService(Context.LOCATION_SERVICE);

        locationListenerp = new MyLocationListener();  
        locationManager.requestLocationUpdates(  
        LocationManager.GPS_PROVIDER, 5000, 10, locationListenerp);




    }

    @Override
    public void onDestroy() {
        locationManager.removeUpdates(locationListenerp);



    }
    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "location Service Started", Toast.LENGTH_LONG).show();



    }

     public class MyLocationListener implements LocationListener {
            @Override
            public void onLocationChanged(Location location) {
                Toast.makeText(getApplicationContext(), "I was here", Toast.LENGTH_LONG).show();
            }
            @Override
            public void onProviderDisabled(String s) {
            }
            @Override
            public void onProviderEnabled(String s) {            
            }
            @Override
            public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
                // TODO Auto-generated method stub

            }
        }
}