Save GoogleApiClient on Activity restart in Bundle

457 views Asked by At

My application has a function of theme change (i.e. Activity is restarting). Is it possible to save somehow GoogleApiClient with its all callbacks state and parameters into Bundle in onSaveInstanceState() so that I don't need to rebuild it every time?

I'm using Google Cast Api Client (for Chromecast devices).

                mApiClient = new GoogleApiClient.Builder(mContext)
                    .addApi(Cast.API, apiOptionsBuilder.build())
                    .addConnectionCallbacks(mConnectionCallbacks)
                    .addOnConnectionFailedListener(mConnectionFailedListener)
                    .build();

            mApiClient.connect();

I found out that it is possible NOT to disconnect() this client. But still mApiClient = null after this.

I have also tried to put mApiClient as savedInstanceState.putParcelable() and savedInstanceState.putSerializeble() but this object isn't parcelable or serializible.

Full code of GoogleApiClient launcher:

 /**
 * 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);
    }
}

It is not really user-friendly to reconnect to Chromecast device every time theme changed. Any solution for this?

1

There are 1 answers

4
siva On BEST ANSWER

You should maintain the googleapiclient connection inside a service rather that in an activity which can get killed during configuration changes. Your theme change has no relation to apiclient object. So it is a good practice if you decouple your UI and core logic to avoid such issues.