后台服务中的 FusedLocationAPI

FusedLocationAPI in Background Service

我正在尝试在后台服务中使用 FusedLocation API。我在 :-

上遇到错误
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleAPIClient, mLocationRequest, this);

要求我将第 3 个参数转换为(转换为 com.google.android.gms.location.LocationListener)。 我尝试这样做,但 App crashed.I 不知道为什么会发生这种情况或要求投射。

服务class的完整代码如下:-

public class LocationBgService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

private GoogleApiClient mGoogleAPIClient;
private LocationRequest mLocationRequest;
private FusedLocationProviderApi mLocationProvider;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();

    mGoogleAPIClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    mLocationProvider = LocationServices.FusedLocationApi;

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(60000);
    mLocationRequest.setFastestInterval(15000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    mGoogleAPIClient.connect();
    return START_STICKY;
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    RequestLocationUpdates();
}

private void RequestLocationUpdates() {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

    }
       LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleAPIClient, mLocationRequest, this); //getting error here..for casting..!

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
public void onLocationChanged(Location location) {
    Log.d("Background Location ", "::::***********Latitude: " + location.getLatitude() + " Longitude: " + location.getLongitude());
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}

我搜索了一下,发现很多人都在使用同一行代码,这就是为什么我会收到这个错误。 我错过了什么事吗?请提前帮我this.Thanks

您可能正在使用旧形式的 LocationListener。看起来您使用的是用于 LocationManager 而不是较新的 LocationServices API.

在您的导入语句中,更改

    import android.location.LocationListener;

对此

    import com.google.android.gms.location.LocationListener;

您需要删除底部的 3 个方法。它们未在较新的 LocationListener 中使用。此外,您可能需要清理并进行全面重建。使用新的导入语句,您的代码对我有用。