我想在我的应用程序中实现基于位置的功能。我一直在阅读,我发现自己有点困惑。
当谷歌搜索教程时,几乎每个结果都会返回一个使用 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 分钟后。