我正在尝试通过运行后台服务来获取连续的位置更新。在调试代码时,将调用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));

最佳答案

什么是您的android手机SDK,您如何请求清单文件的权限?
如果您的手机SDK为23或更高版本,则您请求权限的方式会有所不同。

10-05 21:01
查看更多