【问题标题】:Android: new Google Client API LocationAndroid:新的 Google 客户端 API 位置
【发布时间】:2016-05-26 17:41:06
【问题描述】:

案例:应用程序需要设备位置来指定网络请求。如果位置提供程序被禁用,它应该使用最后一个已知位置。作为android.locationseems to be deprecated in favor of Fused location API,我决定使用新的API,但遇到了一些问题。使用旧 API,我的案例看起来像这样:

//get Location
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
...
bestProvider = locationManager.getBestProvider(criteria, true);

protected void onResume() {
    super.onResume();

    //check providers. If providers disabled, use last known location 
    if (locationManager.isProviderEnabled(bestProvider)) {
        locationManager.requestLocationUpdates(bestProvider, 1000 * 60, 100, this);
    } else {
        Location location = locationManager.getLastKnownLocation(bestProvider);
    }

但我不确定如何在 Fused API 中进行类似操作。新 API 中提供者的可用性如何?因为 Fused Location(GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener) 的新接口没有给我提示。

我想了解的是我的帖子中描述的用例。 如果位置提供程序被禁用,它应该使用最后一个已知位置。因此,核心位置 API 中针对这种情况的条件语句是 isProviderEnabled() 方法的结果。但是新的 API 呢?

【问题讨论】:

    标签: android android-location


    【解决方案1】:

    首先,LocationManager 未被弃用。但它直接使用Android API。 Google Fused Location 依赖于 Google API(不是 Android API,这意味着并非所有手机都默认拥有它)。

    在 Google API 中,您不必担心使用哪个提供商。但是您只需要连接到 API、注册回调、发送请求,仅此而已。

    https://developer.android.com/training/location/receive-location-updates.html

    来自多个 Google 开发者文档:

    这将被放入您的应用程序 build.gradle

    apply plugin: 'com.android.application'
    ...
    
    dependencies {
        compile 'com.google.android.gms:play-services-location:9.0.0'
    }
    

    在你的活动中,应该放这样的东西

     mGoogleApiClient = new GoogleApiClient.Builder(this)
             .addApi(LocationServices.API)
             .addConnectionCallbacks(this)
             .addOnConnectionFailedListener(this)
             .build()
    

    mGoogleApiClient 必须声明为 GoogleApiClient GoogleApiClient mGoogleApiClient;

    当然,这个activity必须实现GoogleApiClient.ConnectionCallbacks,这个有onConnected和onConnectionSuspended两个函数。

    同时实现 GoogleApiClient.OnConnectionFailedListener。这有一个函数 OnConnectionFailed

    在 OnConnectionFailed 中,处理失败(例如,AlertDialog 表示与 Google API 服务相关的错误)

    在 OnConnection 中,你可以这样写

        LocationRequest mLocationRequest = new LocationRequest().setInterval(1000 * 60);
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
    

    注意,活动必须实现 com.google.android.gms.location.LocationListener

    这是一种方式,另一种方式是使用PendingIntent绑定BroadcastReceiver(性能更高但监听方法可以)

    【讨论】:

    • 感谢您的回答,但这部分对我来说很清楚。我想了解的是我的帖子中描述的用例。 如果位置提供程序被禁用,它应该使用最后一个已知位置。因此,核心位置 API 中针对这种情况的条件语句是 isProviderEnabled() 方法的结果。但是新的 API 呢?
    猜你喜欢
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多