java - onCreate 与 onStart 中的 GoogleAPIClient 连接

标签 java android google-play-services google-api-client android-googleapiclient

摘自Google API Client documentation ,

public GoogleApiClient.Builder enableAutoManage (FragmentActivity
fragmentActivity, GoogleApiClient.OnConnectionFailedListener
unresolvedConnectionFailedListener)

Enables automatic lifecycle management in a support library FragmentActivity that connects the client in onStart() and disconnects it in onStop().

It handles user recoverable errors appropriately and calls onConnectionFailed(ConnectionResult) on the unresolvedConnectionFailedListener if the ConnectionResult has no resolution. This eliminates most of the boiler plate associated with using GoogleApiClient.

虽然这听起来有点天真,但我的问题是,这是否是我们在 onStart 方法中启动 GoogleAPIClient 连接的重要步骤?如果我在 onCreate 中建立连接会有什么危害吗?由于遗留代码,我在多个场景中发现需要在 onCreate 中连接到 googleApiClient。我还尝试在 onCreate 中建立连接并且有效(我没有看到任何崩溃)。这是一个坏主意吗?那么为什么在 onStart 中启动连接并在 onStop 中停止连接是必要或重要的呢?

最佳答案

您可以引用这个帖子:What does onStart() really do? - Android

onStart() is called when activity resumes from stopped state. For example, if you have activity A and starts activity B from it, then activity A will be paused (onPause()) and then stopped (onStop()) and moved to back stack. After this, if you press Back into your activity B, B will be paused(onPause()), stopped (onStop()) and destroyed(onDestroy()), and activity A will be restored from back stack, started (onStart()) and resumed(onResume()). As you can see, system will not call onCreate() for A again.

How to use onStart()? For example, you should unregister listeners for GPS, sensors, etc in onStop() and register again in onStart(). If you register it in onCreate() and unregister in onDestroy(), then GPS service will work always and it will drain battery.

还有人说onStart()的主要作用是 Activity 暂停后被调用的时间。如果onCreate()被调用,那么所有的初始化都应该再次完成,通过使用onStart()我们可以初始化那些在onstop()中未初始化的东西。

关于java - onCreate 与 onStart 中的 GoogleAPIClient 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47147863/

相关文章:

java - JDBC 中的连接是什么?

java - 将时间转换为阿拉伯时区

android - SDK 管理器执行 :114 java not found error in Ubuntu while running SDK manager

java - 如何在Android Studio上设置四个图片在不同的角落?

java - 如何检查我的代码中按钮的背景(在我设计的各种可绘制 xml 之间)以便我可以修改它?

java - 如何在新线程中创建Socket

java - 如何在 TabLayout 中自定义选定的选项卡指示器?

android - Google Play 服务 GCM 9.2.0 要求 "update"返回 9.0.0

android - 在模拟器中使用 Google Play 游戏服务

android - 添加 Geofence 使 ApiException 状态为 13