我想使用Google的融合位置API獲取我的位置。爲此,我創建了兩個類。一個是MainActivity,另一個是FusedLocationService,其中MainActivity是主類。但是我的經度和緯度都是0.0。所以請幫助我。無法使用Google的融合位置API獲取位置
這裏是我的MainActivity代碼: -
public class MainActivity extends AppCompatActivity {
TextView tvLocation;
FusedLocationService fusedLocationService;
double latitude;
double longitude;
String locationResult = "";
Location location;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvLocation = (TextView) findViewById(R.id.tvLocation);
fusedLocationService = new FusedLocationService(this);
location = fusedLocationService.getLocation();
if (null != location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
locationResult = "Latitude: " + latitude + "\n" +
"Longitude: " + longitude + "\n";
} else {
Timber.e("-error-%s", "Location Not Available!");
locationResult = "Location Not Available!";
}
Log.e("Lati ", String.valueOf(latitude));
Log.e("longi ", String.valueOf(longitude));
tvLocation.setText(locationResult);
}
}
這裏是我FusedLocationService類: -
public class FusedLocationService implements LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final long INTERVAL = 1000 * 30; //30sec
private static final long FASTEST_INTERVAL = 1000 * 5; // 5sec
Activity mActivity;
public LocationRequest locationRequest;
public GoogleApiClient googleApiClient;
public Location location;
public FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
public FusedLocationService(Activity activity) {
Timber.plant(new Timber.DebugTree());
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
mActivity = activity;
googleApiClient = new GoogleApiClient.Builder(mActivity)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (googleApiClient != null) {
googleApiClient.connect();
}
}
@Override
public void onConnected(Bundle connectionHint) {
Log.e("-onConnected-", "connected now");
location = fusedLocationProviderApi.getLastLocation(googleApiClient);
fusedLocationProviderApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
@Override
public void onLocationChanged(Location location) {
}
public Location getLocation() {
return location;
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
我已經包含在gradle這個文件夾中的體現權限和lib。 所以請幫助。謝謝你在前進
在'onConnected'方法檢查此代碼'googleApiClient.isConnected()'。如果它返回false,那麼應該有一個殘疾人位置的情況下可能在設置電話或谷歌服務。 –