我已经在其他线程中阅读了这个问题的解决方案,但我似乎不明白为什么它返回 null。我使用了谷歌开发者网站中提供的相同片段:https ://developer.android.com/training/location/retrieve-current.html
我在我的活动中使用以下代码来获取用户的当前位置:
public class MainActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener {
protected GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buildGoogleApiClient();
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
}
如果“mLastLocation”始终为空,我们如何编写代码来获取用户的当前位置?