摘自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 callonCreate()
for A again.How to use
onStart()
? For example, you should unregister listeners for GPS, sensors, etc inonStop()
and register again inonStart()
. If you register it inonCreate()
and unregister inonDestroy()
, 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/