【发布时间】:2016-01-09 23:54:35
【问题描述】:
我正在尝试通过onConnected() 方法获取我的当前位置。但不幸的是,onMapReady() 被提前调用。因此,我的变量 currentLatitude 和 currentLongitude 包含值 0.0,您可以在下面的日志中看到:
I/System.out: currentLatitude : 0.0
I/System.out: currentLongitude : 0.0
D/: HostConnection::get() New Host Connection established 0xeec39820, tid 23599
I/System.out: onConnected
我已经尝试使用AsyncTask,但这不起作用,因为onPreExecute() 在onConnected() 之前执行。在这里你可以看到它的截图:
链接:http://i.imgur.com/Ur1ZGbb.png
你可以在下面看到我的代码:
public class BreakDownOnMaps extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
OnMapReadyCallback {
protected GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest = new LocationRequest();
double currentLatitude;
double currentLongitude;
LatLng latLng;
@TargetApi(Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_break_down_on_maps);
buildApi();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
private void buildApi() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public void handleNewLocation(Location loc) {
currentLatitude = loc.getLatitude();
currentLongitude = loc.getLongitude();
latLng = new LatLng(currentLatitude, currentLongitude);
System.out.println("handleNewLocation ");
}
@Override
public void onConnected(Bundle bundle) {
System.out.println("onConnected");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
}
else {
handleNewLocation(location);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
System.out.println("currentLatitude : " + currentLatitude);
System.out.println("currentLongitude : " + currentLongitude);
latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am here!");
googleMap.addMarker(options);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
【问题讨论】:
标签: java android google-api-client locationlistener