簡體   English   中英

在服務中使用GoogleAPIClient獲取位置

[英]get location using GoogleAPIClient in Service

我想在后台獲取位置,以便可以從任何活動/片段中獲取位置。 問題是我沒有在服務中獲得經度和緯度。 我在這里做錯什么了嗎?

 public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private static final String TAG = "sammy_"; private boolean currentlyProcessingLocation = false; private LocationRequest locationRequest; private Location mCurrentLocation; private GoogleApiClient googleApiClient; @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { startTracking(); return START_NOT_STICKY; } private void startTracking() { Log.d(TAG, "startTracking"); googleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); } @Override public void onDestroy() { super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onLocationChanged(Location location) { mCurrentLocation = location; System.out.println("Current LAT: "+mCurrentLocation.getLatitude()+ " Current LANG: "+mCurrentLocation.getLongitude()); } private void stopLocationUpdates() { if (googleApiClient != null && googleApiClient.isConnected()) { googleApiClient.disconnect(); } } @Override public void onConnected(Bundle bundle) { Log.d(TAG, "onConnected"); locationRequest = LocationRequest.create(); locationRequest.setInterval(1000); locationRequest.setFastestInterval(1000); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); /*if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; }*/ if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this); } } @Override public void onConnectionFailed(ConnectionResult connectionResult) { Log.e(TAG, "onConnectionFailed"); stopLocationUpdates(); stopSelf(); } @Override public void onConnectionSuspended(int i) { Log.e(TAG, "GoogleApiClient connection has been suspend"); } } 

看看在服務使用GoogleApiClient

看來您需要連接到Google API(並且還應該將GoogleApi代碼移至onCreate())。

暫無
暫無

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

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