我的应用程序具有主题更改功能(即活动正在重新启动)。是否可以将GoogleApiClient
以及Bundle
中的所有回调状态和参数保存到onSaveInstanceState()
,以便每次都不需要重建它?
我正在使用Google Cast Api客户端(适用于Chromecast设备)。
mApiClient = new GoogleApiClient.Builder(mContext)
.addApi(Cast.API, apiOptionsBuilder.build())
.addConnectionCallbacks(mConnectionCallbacks)
.addOnConnectionFailedListener(mConnectionFailedListener)
.build();
mApiClient.connect();
我发现不可能disconnect()
这个客户端。但在此之后仍然mApiClient = null
。
我还尝试将mApiClient
设为savedInstanceState.putParcelable()
和savedInstanceState.putSerializeble()
,但此对象不是可分割的或可序列化的。
GoogleApiClient启动器的完整代码:
/**
* Start the receiver app
*/
private void launchReceiver() {
try {
mCastListener = new Cast.Listener() {
@Override
public void onApplicationDisconnected(int errorCode) {
Log.d(TAG, "application has stopped");
teardown();
}
};
// Connect to Google Play services
mConnectionCallbacks = new ConnectionCallbacks();
mConnectionFailedListener = new ConnectionFailedListener();
Cast.CastOptions.Builder apiOptionsBuilder = Cast.CastOptions
.builder(mSelectedDevice, mCastListener);
if (mApiClient == null) {
mApiClient = new GoogleApiClient.Builder(mContext)
.addApi(Cast.API, apiOptionsBuilder.build())
.addConnectionCallbacks(mConnectionCallbacks)
.addOnConnectionFailedListener(mConnectionFailedListener)
.build();
mApiClient.connect();
}
} catch (Exception e) {
Log.e(TAG, "Failed launchReceiver", e);
}
}
每次主题更改时重新连接到Chromecast设备并不十分方便用户。对此有何解决方案?
答案 0 :(得分:1)
您应该在服务中维护googleapiclient连接,而不是在配置更改期间可能会被杀死的活动。您的主题更改与apiclient对象无关。因此,如果您将UI和核心逻辑分离以避免此类问题,这是一种很好的做法。