【发布时间】:2015-03-06 19:50:19
【问题描述】:
我想在我的应用中实现基于位置的功能。我读了一点,发现自己有点困惑。
在谷歌上搜索教程时,几乎每个结果都会返回一个使用 Android Location API 的示例。
然而,在阅读 android 开发者指南时,他们声明如下:
Google Play 服务位置 API 优于 Android 框架位置 API (android.location),可作为向您的应用添加位置感知的一种方式。如果您目前正在使用 Android 框架位置 API,强烈建议您尽快切换到 Google Play 服务位置 API。
所以这告诉我不要选择只实现位置监听器的更简单的方法。
所以我的问题是,两者之间有什么区别?为什么我要使用一个而不是另一个?
我在哪里可以找到关于如何安全准确地正确访问 Google Play 服务位置 API 的不错的教程。
到目前为止,我已经尝试过这个(如 Android 网站上所建议的那样),但是我的回调都没有被调用。
public class LocationManager implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private Context mContext;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
public LocationManager(Context context) {
mContext = context;
//
if (checkIfGooglePlayServicesAreAvailable()) {
//Get Access to the google service api
buildGoogleApiClient();
} else {
//Use Android Location Services
//TODO:
}
}
public Location getCoarseLocation() {
if (mLastLocation != null) {
return mLastLocation;
} else return null;
}
private synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
private boolean checkIfGooglePlayServicesAreAvailable() {
int errorCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);
if (errorCode != ConnectionResult.SUCCESS) {
GooglePlayServicesUtil.getErrorDialog(errorCode, (MainActivity) mContext, 0).show();
return false;
}
return true;
}
@Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location != null) {
mLastLocation = location;
Toast.makeText(mContext, location.getLongitude() + " , " + location.getLatitude() + " : " + location.getAccuracy(), Toast.LENGTH_LONG).show();
}
}
@Override
public void onConnectionSuspended(int i) {
Toast.makeText(mContext, "suspended", Toast.LENGTH_LONG).show();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(mContext, connectionResult.toString(), Toast.LENGTH_LONG).show();
}
}
然后我从我的活动中调用我的 LocationManager:
LocationManager locationManager = new LocationManager(this);
Location location = locationManager.getCoarseLocation();
//Use Location
我想创建一个助手类,我可以简单地从任何活动或片段中调用它。 但是,当我运行以下命令时,构造函数执行成功。但是,我在回调中的断点都没有被命中。即使在 1 或 2 分钟后。
【问题讨论】:
-
据我所知,根据您的代码判断,您没有像我记得的那样遵循 Google 指南...您在哪里
requestLocationUpdates()? -
基本上 google 位置 API 是相同的,除了 google 的 android 处理所有不同的位置回调(GPS、网络、Wifi),所以您只需要担心是否获得位置
-
@shkschneider 我只是得到了最后一个已知位置:developer.android.com/training/location/retrieve-current.html 但是我没有在 Activity 中实现它,我正在将 Activity 引用传递给我的班级。
标签: android gps google-play-services location-services