使用服务在后台进行GPS跟踪

时间:2011-12-03 10:28:51

标签: android android-service

我有一个用于收听GPS位置的服务,我想在Toast中显示更新的位置,我通过单击按钮在其他活动中运行该服务。该服务已成功创建,但未显示更新位置的Toast。这是代码:

   public class locationlistening_service extends Service implements LocationListener  {

    static LocationManager locationManager;
    LocationListener locationListener;

    private static final String TAG = "Calculations";
    @Override
    public void onCreate() {
        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");
        run();
    }

    private void run(){

        final Criteria criteria = new Criteria();

        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setSpeedRequired(true);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        //Acquire a reference to the system Location Manager
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        // Define a listener that responds to location updates
        locationListener = new LocationListener() {
              public void onLocationChanged(Location location) 
              {
                 recordLocation(location);
              }

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

              public void onProviderEnabled(String provider) {}

              public void onProviderDisabled(String provider) {}

        };
    }
public void recordLocation(Location loc) 
{
Toast.makeText(locationlistening_service.this,"Lat: " + String.valueOf(loc.getLatitude()) + " Long: " + String.valueOf(loc.getLongitude()),Toast.LENGTH_SHORT).show();

}



    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

    }

    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }



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

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

        }

其他活动中有服务电话。

public void startButton(View view) {

    startService(new Intent(this, locationlistening_service.class));
}

1 个答案:

答案 0 :(得分:1)

你永远不会打电话给requestLocationUpdates()。因此,没有任何内容正在使用您的LocationManagerLocationListenerCriteria

请确保在不再需要时关闭此服务。