如何保持GoogleAPIClient始终连接

时间:2016-05-25 05:30:14

标签: android location google-play-services google-api-client

我正在使用GoogleAPIClient来读取位置信息。我希望这始终是连接的。如何确保始终连接。一种方法是在调用连接失败回调时重新连接它。

触发以下回调的用例是什么? 1.OnConnectionFailedListener - > onConnectionFailed 2. ConnectionCallbacks - > onConnectionSuspended

我试图强制停止谷歌播放服务,但没有得到回调[onConnectionSuspended]

如果GoogleAPIClient始终连接,是否会出现任何问题(电池,性能)?

1 个答案:

答案 0 :(得分:0)

从官方文档中,您可以找到以下内容:

// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
     mGoogleApiClient = new GoogleApiClient.Builder(this)
         .addConnectionCallbacks(mConnectionCallbacks)
         .addOnConnectionFailedListener(mConnectionFailedCallbacks)
         .addApi(LocationServices.API)
         .build();
}
//you will need to specify the callbacks.

//Of course, you will need to connected:
protected void onStart() {
     mGoogleApiClient.connect();
     super.onStart();
}

//Disconnect
protected void onStop() {
     mGoogleApiClient.disconnect();
     super.onStop();
}

//get last location
public Location getLastLocation(){
//you need to be connected. Therefore this must be in the onConnected
//method of the mConnectionCallbacks.
     mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
}

链接:Getting the Last Known Location

修改
连接它(或者我唯一知道的)的唯一用例是当你想要一个跟踪你的位置的服务时,即使应用程序在后台也是如此。
在这里阅读一些有趣的教程:
http://www.101apps.co.za/articles/services-tutorials-part-2-a-foreground-service.html
http://www.edureka.co/blog/android-tutorials-beginners-service-component/
修改2
有关失败连接的详细信息的链接:
1. onConnectionFailed
2. Accessing the Google Api