簡體   English   中英

在后台獲取用戶位置

[英]Get user location in background

我有一個應用程序,其更新用戶位置是它的主要功能。

到目前為止,我有一個可以通過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();
}
 }

我想要的是即使用戶未使用該應用程序也要獲取其位置(我的意思是即使應用程序未啟動並運行時也要獲取其位置),什么是最好的方法?

  • 我應該提供服務並運行它嗎?
  • 如何使用Google Play位置Api 這對我有幫助嗎?

提前致謝。

創建此服務,即使您的應用程序未運行,該服務也將始終在后台運行。

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM