我试图通过运行后台服务来获得连续的位置更新。在调试代码时,调用了onConnected(Bundle b),并调用了位置更新请求。但是onLocationChanged( 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文档的时候,我不明白我在哪里犯了错误。我正在测试真实的设备和应用程序的位置权限。
最优惠服务:
<service
android:name=".locations.LocationUpdateService"
android:enabled="true"
android:exported="false"></service>
活动中的服务召唤:
startService(new Intent(BaseActivity.this, LocationUpdateService.class));
发布于 2017-05-17 07:00:24
您的android是什么?您是如何要求清单文件的权限的?如果您的phone SDK是23或更高,则请求权限的方式是不同的。
发布于 2017-05-19 01:55:33
这只是一个愚蠢的调试问题。我发现我的设备位置访问在预先设置是关闭的。
https://stackoverflow.com/questions/44022751
复制相似问题