我正在尝试在后台服务中使用FusedLocation API。我收到错误: -
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleAPIClient, mLocationRequest, this);
要求我将第3个参数转换为(强制转换为com.google.android.gms.location.LocationListener)。 我试图这样做并且App崩溃。我没有任何想法为什么会发生这种情况或者要求施放。
服务类的完整代码如下: -
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) {
}
}
我搜索过,发现很多人都在使用同一行代码,所以为什么我会收到这个错误。 我错过了要做什么或做什么?请帮帮我。谢谢你。
答案 0 :(得分:3)
您可能正在使用旧版本的LocationListener。看起来你正在使用的是LocationManager而不是更新的LocationServices API。
在导入语句中,更改
import android.location.LocationListener;
到此
import com.google.android.gms.location.LocationListener;
您需要删除底部的3种方法。它们不在较新的LocationListener中使用。此外,您可能需要清洁&做一个完整的重建。使用新的import语句,您的代码适合我。