【发布时间】:2017-05-17 10:50:31
【问题描述】:
我正在尝试通过运行后台服务来获取持续的位置更新。当我调试代码 onConnected(Bundle b) 并调用位置更新请求时。但是永远不会调用 onLocationChanged(Location location)。以下是我的代码:
public class LocationUpdateService extends Service implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleApiClient googleApiClient;
private LocationRequest mLocationRequest;
Location mCurrentLocation;
@Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
double lat = mCurrentLocation.getLatitude();
double lng = mCurrentLocation.getLongitude();
}
//GoogleApiClient
@Override
public void onConnectionFailed(ConnectionResult bundle) {
}
@Override
public void onConnected(Bundle bundle) {
Log.i("onConnected", "GoogleApiClient");
Toast.makeText(this, "Location service connected", Toast.LENGTH_SHORT).show();
createLocationRequest();
startLocationUpdate();
}
@Override
public void onConnectionSuspended(int i) {
}
//Service
@Override
public void onCreate() {
super.onCreate();
buildGoogleApiClient();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY; // run until explicitly stopped.
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void startLocationUpdate() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
googleApiClient, mLocationRequest, this);
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
void createLocationRequest() {
mLocationRequest = new LocationRequest().create()
.setInterval(5000)
.setFastestInterval(5000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
}
我不明白我在哪里犯错,虽然我关注了android docs。我正在真实设备上进行测试,并且应用具有位置权限。
清单中的服务:
<service
android:name=".locations.LocationUpdateService"
android:enabled="true"
android:exported="false"></service>
活动中的服务调用:
startService(new Intent(BaseActivity.this, LocationUpdateService.class));
【问题讨论】:
-
首先,您必须在清单文件中提及此服务,然后您应该将此服务绑定到您的任何活动或片段
-
@Bhavnik 我已经在清单中提到了服务,服务也从活动开始。在调试时,我遇到了 OnConnected() 方法。但从来没有接到 onLocationChanged 的电话
标签: android google-maps geolocation google-api-client