1
我想在後臺服務中使用FusedLocation API。我對收到錯誤: -FusedLocationAPI在後臺服務
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleAPIClient, mLocationRequest, this);
問我的第三個參數澆鑄成(轉換成com.google.android.gms.location.LocationListener)。 我試圖這樣做,應用程序崩潰。我沒有任何想法爲什麼發生這種情況或要求投。
所述服務類完整的代碼如下: -
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) {
}
}
我搜索,發現很多人都在使用相同的代碼行,爲什麼我得到這個錯誤。 我錯過了什麼或做什麼?請幫助我這個。感謝提前。
Thankz man.Such a blunder。我實現了這個'com.google.android.gms.location.LocationListener'並且工作正常。還有一件事。當GPS關閉時,上面的代碼可以獲得使用網絡提供商的用戶的位置。至於現在我只有在GPS打開時才能獲取用戶的位置。我在Manifest文件中添加了FINE&COARSE權限。我需要添加其他東西嗎? –