Persist Google Play Services login between activit

2020-04-12 10:14发布

问题:

I thought this would be straightforward, but I've been going in circles trying to figure out how to keep a user logged in between Activities.

I have a "Main" and a "Details" Activity. A user logs into Google Play Services in the "Main" Activity and I want to submit achievements and leaderboard data in the "Details" Activity.

I'm inheriting from BaseGameActivity in both Activities and using:

 mGoogleApiClient = getApiClient();

in "Details", however when I call isConnected it always returns false.

I even tried copying all the login/callback code from the "Main" Activity over, but it's still doesn't detect the user is logged in.

This post suggests not using BaseGameActivity and pass GameHelper using a singleton:

How to use BaseGameActivity.getApiClient() in multiple activities?

Not sure what the correct approach is.

回答1:

The most simple way to do this is to have both activities create a separate instance of the api client. The state of the connection is shared between them internally, so you don't need worry about how to pass around the client and handle callbacks that may happen when an activity is not active, and the player will only log in on your main activity.

Extending your activity from BaseGameActivity really is not needed any longer (for an entertaining explanation watch: Death of BasegameActivity. What you do need to do is implement the two interfaces that handle initializing the GoogleAPIClient:

public class MainActivity extends Activity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {
        }

To implement these, refer to the samples and the doc: https://developers.google.com/games/services/android/init