我创建了以下代码,只需获取最新的纬度和经度,无需用户打开GPS,只需依靠wifi或网络进行定位。在运行应用程序时,它只返回Toast“The Lat is 0.0 and Long is 0.0”。我知道这应该有用,因为我在这里下载了示例代码:https://github.com/googlesamples/android-play-location/tree/master/BasicLocationSample,并且适合在我的代码中工作。
我怎样才能让它发挥作用?
public class MainActivity extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, OnConnectionFailedListener {
public static double lat;
public static double lng;
ViewPager viewPager = null;
/**
* Provides the entry point to Google Play services.
*/
protected GoogleApiClient mGoogleApiClient;
/**
* Represents a geographical location.
*/
protected Location mLastLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buildGoogleApiClient();
String text = "The Lat is " + lat
+ " and Long is " + lng;
Toast.makeText(getBaseContext(), text, Toast.LENGTH_LONG).show();
};
// Assign list to actionbar
actionBar.setListNavigationCallbacks(aAdpt, null); // DEPRACATED
}
/**
* Builds a GoogleApiClient. Uses the addApi() method to request the LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
@Override
public void onConnected(Bundle connectionHint) {
// Provides a simple way of getting a device's location and is well suited for
// applications that do not require a fine-grained location and that do not need location
// updates. Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
lat = mLastLocation.getLatitude();
lng = mLastLocation.getLongitude();
} else {
Toast.makeText(this,"No location detected", Toast.LENGTH_LONG).show();
}
}
@Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
}
@Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
mGoogleApiClient.connect();
}
}
}
答案 0 :(得分:2)
" lat"," lng"," mLastLocation"在执行onConnected()之前,设置或有效。您需要了解此操作是异步 - 也就是说,该位置不会立即返回,但稍后会提供。如果您测试了是否" mLastLocation"这将是显而易见的。当你做吐司时,它是否为空。