在后台获取用户位置

时间:2015-06-02 04:14:46

标签: android gps location

我有一个应用程序,更新用户位置是它的主要功能。

到目前为止,我有一个通过GPS和NETWORK提供商获取用户位置的课程。它运作得很好:

 public class UserLocation {
private String TAG = "UserLocation";
Timer timer;
LocationManager locationManager;
OnLocationResultListener listener;
boolean gps_enabled = false;
boolean network_enabled = false;


public UserLocation setListener(OnLocationResultListener listener) {
    this.listener = listener;
    return this;
}

public boolean getLocation() {

    if (locationManager == null) {
        locationManager = (LocationManager) G.context.getSystemService(Context.LOCATION_SERVICE);
    }

    //exceptions will be thrown if provider is not permitted.
    try {
        gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex) {
        Log.e(TAG, "Location GPS_PROVIDER is off");
        ex.printStackTrace();
    }
    try {
        network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {
        Log.e(TAG, "Location NETWORK_PROVIDER is off");
        ex.printStackTrace();
    }

    timer = new Timer();
    timer.schedule(new GetLastLocation(), 0, GlobalConsts.LOCATION_RECHECK_TIME);
    return true;
}


LocationListener gpslocationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        Log.e(TAG, "Calling gpslocationListener==> onLocationChanged");
        timer.cancel();

        listener.onGotLocation(location);
        locationManager.removeUpdates(gpslocationListener);
        locationManager.removeUpdates(networklocationListener);
    }

    public void onProviderDisabled(String provider) {
    }

    public void onProviderEnabled(String provider) {
    }

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

LocationListener networklocationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        Log.e(TAG, "Calling networklocationListener==> onLocationChanged");
        timer.cancel();
        listener.onGotLocation(location);
        locationManager.removeUpdates(networklocationListener);
        locationManager.removeUpdates(gpslocationListener);
    }

    public void onProviderDisabled(String provider) {
    }

    public void onProviderEnabled(String provider) {
    }

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

class GetLastLocation extends TimerTask {
    @Override
    public void run() {
        Log.e(TAG, "Getting last location in TimeTask ");
        locationManager.removeUpdates(gpslocationListener);
        locationManager.removeUpdates(networklocationListener);

        Location net_loc = null, gps_loc = null;
        if (gps_enabled)
            gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (network_enabled)
            net_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        //if there are both values use the latest one
        if (gps_loc != null && net_loc != null) {
            if (gps_loc.getTime() > net_loc.getTime())
                listener.onGotLocation(gps_loc);
            else
                listener.onGotLocation(net_loc);
            return;
        }

        if (gps_loc != null) {
            listener.onGotLocation(gps_loc);
            return;
        }
        if (net_loc != null) {
            listener.onGotLocation(net_loc);
            return;
        }
        if (gps_loc == null && net_loc == null) {
            Log.e(TAG, "tried to get location in Timetask but both location was null");
        } else if (gps_loc == null) {
            Log.e(TAG, "gps_loc is null in time task");
        } else {
            Log.e(TAG, "net_loc is null in time task");

        }
        listener.onGotLocation(null);
    }
}

public interface OnLocationResultListener {
    void onGotLocation(Location location);

    void onNoLocationProvider();
}
 }

我想要的是获取用户位置,即使他没有使用该应用程序(我的意思是在它发生变化时获取其位置,即使应用程序未启动并运行) 实现这一目标的最佳方法是什么?

提前致谢。

1 个答案:

答案 0 :(得分:3)

创建此服务,即使您的应用程序未运行,该服务也将始终在后台运行。

public class MyLocationService extends Service implements LocationListener,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {

private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;

public MyLocationService() {

}

@Override
public void onCreate() {
    super.onCreate();

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API).
                    addConnectionCallbacks(this).
                    addOnConnectionFailedListener(this)
            .build();

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    mGoogleApiClient.connect();
    Toast.makeText(this, "Location services started", Toast.LENGTH_SHORT).show();
    return super.onStartCommand(intent, flags, startId);
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public void onLocationChanged(Location location) {
    System.out.println("MyLocationService.onLocationChanged");
    // do your work here with location 
}

@Override
public void onConnected(Bundle bundle) {

    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(1000); // Update location every second

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    Location loc = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}


@Override
public void onDestroy() {

    Toast.makeText(this, "Location services stopped", Toast.LENGTH_LONG).show();

    Location loc = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    mGoogleApiClient.disconnect();
    super.onDestroy();
}

}