2017-01-27 2 views
0

Я пытаюсь внедрить службы GooglePlayGamesServices, я попытался следовать за trivial quest and type a number examples, разница в том, что я хочу обновлять оценки и достижения во многих различных действиях, поэтому я сделал статический класс, чтобы помочь с этим, поскольку следующий:Ошибка подключения к игровым сервисам Google Play

import android.content.Context; 
import android.content.Intent; 
import android.os.Bundle; 
import android.support.annotation.NonNull; 
import android.support.annotation.Nullable; 
import android.view.View; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.games.Games; 

/** 
* Created by OSDON on 1/18/2017. 
*/ 

public class PlayServicesUtilities 
{ 
    static boolean firsttime=true; 
    static GoogleApiClient mGoogleApiClient; 


    public static void SetScore(int score, Context context) 
    { 
     if (mGoogleApiClient!=null&& mGoogleApiClient.isConnected()) 
     { 
      Games.Leaderboards.submitScore(mGoogleApiClient,context.getString(R.string.leaderboard_best_score),score); 
     } 
    } 

    public static Intent LeaderBoard(Context context) 
    { 
     if (mGoogleApiClient!=null&&mGoogleApiClient.isConnected()) 
      return Games.Leaderboards.getLeaderboardIntent(mGoogleApiClient,context.getString(R.string.leaderboard_best_score)); 
     return null; 
    } 

    public static Intent Achievements(){ 
     if (mGoogleApiClient!=null&&mGoogleApiClient.isConnected()) 
      return Games.Achievements.getAchievementsIntent(mGoogleApiClient); 
     return null; 
    } 
} 

и я реализовал соединение АФИ в моей основной деятельности следующим образом:

import android.app.Dialog; 
import android.content.ComponentName; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentSender; 
import android.content.ServiceConnection; 
import android.content.pm.PackageManager; 
import android.content.res.Configuration; 
import android.content.res.Resources; 
import android.graphics.BitmapFactory; 
import android.net.Uri; 
import android.os.Bundle; 
import android.support.annotation.NonNull; 
import android.support.annotation.Nullable; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.LinearLayoutCompat; 
import android.util.DisplayMetrics; 
import android.util.Log; 
import android.view.View; 
import android.view.Window; 
import android.widget.Button; 
import android.widget.FrameLayout; 
import android.widget.ImageButton; 
import android.widget.LinearLayout; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.SignInButton; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.games.Games; 
import com.google.android.gms.games.Player; 
import com.google.example.games.basegameutils.BaseGameUtils; 


import java.util.Locale; 

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener 
{ 
    ImageButton playButton,settingsButton,leaderboard,achievements; 
    Button signOut; 
    boolean quitingApp=true; 
    FrameLayout frameLayout; 

    com.google.android.gms.common.SignInButton signIn; 
    private boolean mSignInClicked; 

    // Request code used to invoke sign in user interactions. 
    private static final int RC_SIGN_IN = 9001; 
    private static final int LEADERBOARD=1001; 

    // Are we currently resolving a connection failure? 
    private boolean mResolvingConnectionFailure = false; 

    // Set to true to automatically start the sign in flow when the Activity starts. 
    // Set to false to require the user to click the button in order to sign in. 
    private boolean mAutoStartSignInFlow = false; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     //region PlayServices 
     // Create the Google Api Client with access to Games 
     //if (PlayServicesUtilities.mGoogleApiClient==null) 
     PlayServicesUtilities.mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(Games.API) 
       .addScope(Games.SCOPE_GAMES) 
       .build(); 
     new Runnable(){ 
      @Override 
      public void run() { 
       signIn= (SignInButton) findViewById(R.id.button_sign_in); 
       signOut=(Button)findViewById(R.id.button_sign_out); 
       signIn.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View view) { 
         mSignInClicked = true; 
         PlayServicesUtilities.mGoogleApiClient.connect(); 
        } 
       }); 
       signOut.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View view) { 
         mSignInClicked = false; 
         if (PlayServicesUtilities.mGoogleApiClient!=null&&PlayServicesUtilities.mGoogleApiClient.isConnected()){ 
          Games.signOut(PlayServicesUtilities.mGoogleApiClient); 
          PlayServicesUtilities.mGoogleApiClient.disconnect(); 
         } 
         showSignInBar(); 
        } 
       }); 
      } 
     }.run(); 
     InitiateScoresAchievementsUnlocking(dataProvider.getScore(User.CurrentUser.getId()),getBaseContext()); 
     //endregion 

     frameLayout= (FrameLayout) findViewById(R.id.main_popupFrame); 

     leaderboard= (ImageButton) findViewById(R.id.main_leaderBoard); 
     leaderboard.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) 
      { 
       Intent intent=PlayServicesUtilities.LeaderBoard(getBaseContext()); 
       if (intent!=null) 
       { 
        quitingApp=false; 
        startActivityForResult(intent,LEADERBOARD); 
       } 
       else 
        alertView(getString(R.string.you_need_to_sign_in)); 
      } 
     }); 
     achievements= (ImageButton) findViewById(R.id.main_achievement); 
     achievements.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       SoundEffects.ButtonClick(getBaseContext()); 
       Intent intent=PlayServicesUtilities.Achievements(); 
       if (intent!=null){ 
        quitingApp=false; 
        startActivityForResult(intent,LEADERBOARD); 
       } 
       else 
        alertView(getString(R.string.you_need_to_sign_in)); 
      } 
     }); 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (requestCode == RC_SIGN_IN) { 
      mSignInClicked = false; 
      mResolvingConnectionFailure = false; 
      if (resultCode == RESULT_OK) { 
       PlayServicesUtilities.mGoogleApiClient.connect(); 
      } else 
      { 
       BaseGameUtils.showActivityResultError(this,requestCode,resultCode, R.string.signin_other_error); 
      } 
     } 
     if (requestCode==LEADERBOARD) 
     { 
     } 
    } 

    private void alertView(String message) 
    { 
     final Dialog alertDialog=new Dialog(MainActivity.this); 
     alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
     alertDialog.setContentView(R.layout.alert_dialog); 
     alertDialog.show(); 

     TextView textView= (TextView) alertDialog.findViewById(R.id.alert_dialog_text); 
     textView.setText(message); 
     Button button= (Button) alertDialog.findViewById(R.id.alert_dialog_ok); 
     button.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       alertDialog.dismiss(); 
      } 
     }); 
    } 

    //region playServices 
    // Shows the "sign in" bar (explanation and button). 
    private void showSignInBar() 
    { 
     findViewById(R.id.sign_in_bar).setVisibility(View.VISIBLE); 
     findViewById(R.id.sign_out_bar).setVisibility(View.GONE); 
    } 

    // Shows the "sign out" bar (explanation and button). 
    private void showSignOutBar() { 
     findViewById(R.id.sign_in_bar).setVisibility(View.GONE); 
     findViewById(R.id.sign_out_bar).setVisibility(View.VISIBLE); 
    } 

    @Override 
    public void onConnected(@Nullable Bundle bundle) 
    { 
     showSignOutBar(); 
     PlayServicesUtilities.mGoogleApiClient.connect(); 
     if (PlayServicesUtilities.firsttime&& PlayServicesUtilities.mGoogleApiClient.isConnected()){ 
      Player p = Games.Players.getCurrentPlayer(PlayServicesUtilities.mGoogleApiClient); 
      String displayName; 
      if (p == null) { 
       displayName = ""; 
      } else { 
       displayName = p.getDisplayName(); 
      } 
      if (!displayName.equals("")){ 
       Toast.makeText(getBaseContext(),getString(R.string.hello).replace("[0]",displayName),Toast.LENGTH_SHORT).show(); 
       PlayServicesUtilities.firsttime=false; 
      } 
     } 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 
     PlayServicesUtilities.mGoogleApiClient.connect(); 
    } 

    @Override 
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) 
    { 
     if (mResolvingConnectionFailure) 
     { 
      return; 
     } 

     if (mSignInClicked || mAutoStartSignInFlow) 
     { 
      mAutoStartSignInFlow = false; 
      mSignInClicked = false; 
      mResolvingConnectionFailure = BaseGameUtils.resolveConnectionFailure(this,PlayServicesUtilities.mGoogleApiClient,connectionResult, RC_SIGN_IN, getString(R.string.signin_other_error)); 
     } 
     showSignInBar(); 
    } 

    @Override 
    protected void onStop() { 
     super.onStop(); 
     if (quitingApp&&PlayServicesUtilities.mGoogleApiClient.isConnected()) { 
      PlayServicesUtilities.mGoogleApiClient.disconnect();} 
    } 

    @Override 
    protected void onStart() { 
     super.onStart(); 
     if(PlayServicesUtilities.firsttime) 
     { 
      PlayServicesUtilities.mGoogleApiClient.connect(); 
      PlayServicesUtilities.firsttime=false; 
     } 
    } 
    //endregion 


    void InitiateScoresAchievementsUnlocking(int currentScore,Context context) 
    { 
     String achievements[]=context.getResources().getStringArray(R.array.achievements); 
     int achievementsNeededScore[]=context.getResources().getIntArray(R.array.achievements_needed_scores); 

     if (PlayServicesUtilities. mGoogleApiClient.isConnected()) 
      for (int i=0;i<achievements.length;i++) 
      { 
       if (currentScore>=achievementsNeededScore[i]) 
       { 
        Games.setViewForPopups(PlayServicesUtilities.mGoogleApiClient,frameLayout); 
        Games.Achievements.unlock(PlayServicesUtilities.mGoogleApiClient,achievements[i]); 
       } 
      } 
    } 
} 

проблема является:

1- (эмулятор), когда я запустить приложение и выйти playservices и войти в системе, и если я просить лидер плату alertView(getString(R.string.you_need_to_sign_in)); получила

срабатывает

2- (В реальном устройстве) даже не войти игровые услуги, которые она показать быстрый диалог об ошибке «Не удалось войти ...» и активность перезагружать

ответ

0

Как указывается в документации - Troubleshooting Issues in Your Android Game:

Если вы не в состоянии подписать игроков в игре, сначала убедитесь, что вы выполнили инструкции до create your client IDs и configure the games services. Если вы все еще сталкиваетесь с ошибками входа в систему, проверьте следующие пункты, чтобы убедиться, что ваша игра настроена правильно.

Возможно, вы захотите проверить документацию выше, чтобы проверить, где вы столкнулись с проблемой.

Надеюсь, это поможет.

Смежные вопросы