我在我的应用中实施了Google Play游戏,但它确实有效。
但是当我尝试在离线模式下使用应用程序而没有连接互联网时,我遇到了问题,因为它再次要求我登录。
似乎登录会话已过期或类似,因为这会在成功登录后30分钟或1小时发生。
这是我的代码:
public class MainActivity extends Activity implements MainMenuFragment.Listener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
GameFragment.Listener, ResultFragment.Listener {
//Fragments
MainMenuFragment mMainFragment;
GameFragment mGameFragment;
ResultFragment mResultFragment;
// Client used to interact with Google APIs
private GoogleApiClient mGoogleApiClient;
// Are we currently resolving a connection failure?
private boolean mResolvingConnectionFailure = false;
// Has the user clicked the sign-in button?
private boolean mSignInClicked = false;
// Automatically start the sign-in flow when the Activity starts
private boolean mAutoStartSignInFlow = true;
// request codes we use when invoking an external activity
private static final int RC_RESOLVE = 5000;
private static final int RC_UNUSED = 5001;
private static final int RC_SIGN_IN = 9001;
//Debug
private String TAG = "IGRA";
//Shared Preferences stuff
private SharedPreferences mPrefs;
public static final String PREFS_NAME = "TheButtonChallenge";
private SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set activity to be the full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
// Create the Google API Client with access to Plus and Games
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API).addScope(Plus.SCOPE_PLUS_LOGIN)
.addApi(Games.API).addScope(Games.SCOPE_GAMES)
.build();
Log.d(TAG, "activity on created");
//Fragments
mMainFragment = new MainMenuFragment();
mGameFragment = new GameFragment();
mResultFragment = new ResultFragment();
// listen to fragment events
mMainFragment.setListener(this);
mGameFragment.setListener(this);
mResultFragment.setListener(this);
// add initial fragment (welcome fragment)
if (savedInstanceState == null) {
Log.d(TAG, "activity on created savedInstanceState");
getFragmentManager().beginTransaction().add(R.id.container, mMainFragment).commit();
}
mPrefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
editor = mPrefs.edit();
}
// Switch UI to the given fragment
void switchToFragment(Fragment newFrag) {
Log.d(TAG, "switch fragment");
getFragmentManager().beginTransaction().replace(R.id.container, newFrag)
.commitAllowingStateLoss();
}
private boolean isSignedIn() {
return (mGoogleApiClient != null && mGoogleApiClient.isConnected());
}
@Override
protected void onStart() {
super.onStart();
if(!isSignedIn()) {
Log.d(TAG, "onStart(): connecting");
mGoogleApiClient.connect();
}
else{
}
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop(): disconnecting");
/*if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}*/
}
@Override
public void onStartGameRequested() {
Log.d(TAG, "new game");
startGame();
}
@Override
public void onShowAchievementsRequested() {
if (isSignedIn()) {
startActivityForResult(Games.Achievements.getAchievementsIntent(mGoogleApiClient),
RC_UNUSED);
} else {
BaseGameUtils.makeSimpleDialog(this, getString(R.string.achievements_not_available)).show();
}
}
@Override
public void onShowLeaderboardsRequested() {
if (isSignedIn()) {
startActivityForResult(Games.Leaderboards.getAllLeaderboardsIntent(mGoogleApiClient),
RC_UNUSED);
} else {
BaseGameUtils.makeSimpleDialog(this, getString(R.string.leaderboards_not_available)).show();
}
}
@Override
public int getHighScore() {
return mPrefs.getInt("highScore", 0);
}
void startGame(){
switchToFragment(mGameFragment);
}
public void onEnteredScore(int finalScore){
mResultFragment.setFinalScore(finalScore);
// push those accomplishments to the cloud, if signed in
pushAccomplishments(finalScore);
// check for achievements
checkForAchievements(finalScore);
// switch to the exciting "you won" screen
switchToFragment(mResultFragment);
}
/**
* Check for achievements and unlock the appropriate ones.
*
* @param finalScore the score the user got.
*/
void checkForAchievements(int finalScore) {
int playCounter = mPrefs.getInt("playCounter", 0);
int highScore = mPrefs.getInt("highScore", 0);
playCounter++;
Log.d("FINAL SCORE:" , String.valueOf(finalScore));
Log.d("HIGH SCORE: ", String.valueOf(highScore));
editor.putInt("playCounter", playCounter);
editor.commit();
if(finalScore>highScore){
editor.putInt("highScore", finalScore);
editor.commit();
mResultFragment.setHighScore(finalScore);
}
if(playCounter == 1){
Games.Achievements.unlock(mGoogleApiClient, getString(R.string.achievement_first_time_play));
}
// Check if each condition is met; if so, unlock the corresponding
// achievement.
if (finalScore >= 50) {
//achievementToast(getString(R.string.achievement_arrogant_toast_text));
Games.Achievements.unlock(mGoogleApiClient, getString(R.string.achievement_win_50_points));
}
if (finalScore >= 80) {
Games.Achievements.unlock(mGoogleApiClient, getString(R.string.achievement_win_80_points));
}
if (finalScore >= 100) {
// achievementToast(getString(R.string.achievement_leet_toast_text));
Games.Achievements.unlock(mGoogleApiClient, getString(R.string.achievement_win_100_points));
}
if(finalScore >= 150){
Games.Achievements.unlock(mGoogleApiClient, getString(R.string.achievement_win_150_points));
}
if(finalScore >= 200){
Games.Achievements.unlock(mGoogleApiClient, getString(R.string.achievement_win_200_points));
}
}
void achievementToast(String achievement) {
// Only show toast if not signed in. If signed in, the standard Google Play
// toasts will appear, so we don't need to show our own.
if (!isSignedIn()) {
Toast.makeText(this, getString(R.string.achievement) + ": " + achievement,
Toast.LENGTH_LONG).show();
}
}
private void pushAccomplishments(int finalScore) {
if (!isSignedIn()) {
// can't push to the cloud, so save locally
// mOutbox.saveLocal(this);
Log.d(TAG, "can't push to the cloud, so save locally");
return;
}
Games.Leaderboards.submitScore(mGoogleApiClient, getString(R.string.number_guesses_leaderboard),
finalScore);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected(): connected to Google APIs");
// Show sign-out button on main menu
//mMainFragment.setShowSignInButton(false);
// Show "you are signed in" message on win screen, with no sign in button.
//mWinFragment.setShowSignInButton(false);
// Set the greeting appropriately on main menu
Player p = Games.Players.getCurrentPlayer(mGoogleApiClient);
String displayName;
if (p == null) {
Log.w(TAG, "mGamesClient.getCurrentPlayer() is NULL!");
displayName = "???";
} else {
displayName = p.getDisplayName();
Log.d(TAG, displayName);
}
mMainFragment.setGreeting("Hello, " + displayName);
// if we have accomplishments to push, push them
/*if (!mOutbox.isEmpty()) {
pushAccomplishments();
Toast.makeText(this, getString(R.string.your_progress_will_be_uploaded),
Toast.LENGTH_LONG).show();
}*/
}
@Override
public void onWinScreenDismissed() {
switchToFragment(mGameFragment);
}
@Override
public void onWinScreenSignInClicked() {
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == RC_SIGN_IN) {
mSignInClicked = false;
mResolvingConnectionFailure = false;
if (resultCode == RESULT_OK) {
mGoogleApiClient.connect();
} else {
BaseGameUtils.showActivityResultError(this, requestCode, resultCode,
R.string.signin_failure, R.string.signin_other_error);
}
}
}
@Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "onConnectionSuspended(): attempting to connect");
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed(): attempting to resolve");
if (mResolvingConnectionFailure) {
Log.d(TAG, "onConnectionFailed(): already resolving");
return;
}
if (mSignInClicked || mAutoStartSignInFlow) {
mAutoStartSignInFlow = false;
mSignInClicked = false;
mResolvingConnectionFailure = true;
// if (Utils.isConnected(getApplicationContext())) {
if (!BaseGameUtils.resolveConnectionFailure(this, mGoogleApiClient, connectionResult,
RC_SIGN_IN, getString(R.string.signin_other_error))) {
mResolvingConnectionFailure = false;
}
//}
//else{
// Log.d("IGRA", "Nema Interenta");
// }
}
// Sign-in failed, so show sign-in button on main menu
mMainFragment.setGreeting(getString(R.string.signed_out_greeting));
//mMainMenuFragment.setShowSignInButton(true);
// mWinFragment.setShowSignInButton(true);
}