【发布时间】:2016-11-06 15:17:29
【问题描述】:
我有以下简单的课程,这是我的主要活动。我基本上是按照 Android 文档中的这个逐字记录的。我正在通过 Android Studio 从我的手机运行它。我遇到的问题是我绝对从来没有从这个设置中得到一个合法的位置。 location 对象始终为空。实际上,我希望位置 立即 以类似于浏览器通过 navigator.geolocation 快速获取位置的方式。
我的设置方式有什么奇怪的地方吗?如果不是,我如何强制使用 Fused Location Provider API 之外的位置?
public class MyActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private Location location;
private GoogleApiClient mGoogleApiClient;
private static LocationRequest locationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
@Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
@Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
private void requestLocationUpdates() {
locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(500);
}
@Override
public void onConnected(@Nullable Bundle bundle) {
requestLocationUpdates();
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
location = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
@Override
public void onLocationChanged(Location location) {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
@Override
public void onConnectionSuspended(int i) {}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {}
}
【问题讨论】:
-
您的问题解决了吗?有同样的问题
标签: android geolocation fusedlocationproviderapi android-fusedlocation