如何在Android Studio中的应用中实施Google Play游戏服务?

时间:2015-03-05 21:04:19

标签: java android android-studio google-play-services google-play-games

我正在努力弄清楚如何在我的应用中实施Google Play游戏服务。在Google Play开发者控制台上,我使用SHA1键将游戏与相关应用相关联,我知道如何在此处添加排行榜和成就。我还将Google Play服务和Google Repository安装到Android Studio,并将依赖项添加到build.gradle(如此处所述:http://developer.android.com/google/play-services/setup.html)但我不确定如何执行最后2该页面上的步骤(创建Proguard例外并确保设备具有Google Play服务APK)以及是否有必要 - 后者即使是Google Play游戏示例项目似乎也没有。

此外,我不确定实际需要在我的项目中添加哪些代码来启用排行榜和成就,因为根据本指南:https://developers.google.com/games/services/android/achievements,我使用此代码:

Games.Achievements.unlock(mGoogleApiClient, "my_achievement_id");
例如,

解锁成就,但没有关于我如何设置mGoogleApiClient的说明。 我看过示例项目,但目前还不清楚我应该做什么。我的意思是将所有代码复制并粘贴到我的项目中吗?我应该复制和粘贴某些部分吗?我是否必须编写自己的代码才能登录Google Play游戏?

1 个答案:

答案 0 :(得分:0)

您应该使用getApiClient()而不是mGoogleApiClient。

假设您的活动布局包含四个按钮:

 Leaderboard button - To launch the leaderboards,
 Achievement button - To launch achievements
 Sign in and Sign out buttons

对于排行榜,我们会推送best minutes, best distance covered and an overall highscore的分数。

为了取得成就,我们会根据某些条件解锁四项成就 - survivor, warrior, lord, pride

以下是你如何去做的事情:

public class GMSActivity extends BaseGameActivity implements OnClickListener{
    Button lead;
    Button achv;
    final int RC_RESOLVE = 5000, RC_UNUSED = 5001;
//your game score. so we can push to cloud
    int hS = 0; 
//flags for achievements
   boolean survivor;
   boolean tribalWarriror;
   boolean akonfemLord;
   boolean zuluPride;
   LinearLayout signInBar;
   LinearLayout signOutBar;
    Resources r;
    private float bestTimeInSeconds;
    private int bestTimeInMinutes;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
            super.onCreate(savedInstanceState);
            setContentView(R.layout.gms_layout);
            r = getResources();
            lead = (Button)findViewById(R.id.leaderboards);
            achv = (Button)findViewById(R.id.achievements);
            hS = loadScores();
            findViewById(R.id.sign_in_button).setOnClickListener(this);
            findViewById(R.id.sign_out_button).setOnClickListener(this);


            lead.setOnClickListener(this);
            achv.setOnClickListener(this);


               signInBar = (LinearLayout)findViewById(R.id.sign_in_bar);
               signOutBar = (LinearLayout)findViewById(R.id.sign_out_bar);


            checkForAchievements();
             if (isSignedIn()) {
                 onSignInSucceeded();
             }else{
                onSignInFailed();
             }


        }



        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
              if(v == lead){
                  if (isSignedIn()) {
                        startActivityForResult(Games.Leaderboards.getAllLeaderboardsIntent(getApiClient()), RC_UNUSED);
                    } else {
                        showAlert(getString(R.string.leaderboards_not_available));
                    }
            }else if(v ==achv){
                 if (isSignedIn()) {
                        startActivityForResult(Games.Achievements.getAchievementsIntent(getApiClient()), RC_UNUSED);
                    } else {
                        showAlert(getString(R.string.achievements_not_available));
                    }

            }else if(v.getId() == R.id.sign_in_button){
                beginUserInitiatedSignIn();

            }else if(v.getId() == R.id.sign_out_button){
                  signOut();
                  hello.setText(getString(R.string.signed_out_greeting));
                    signInBar.setVisibility(View.VISIBLE);
                    signOutBar.setVisibility(View.GONE);

        }



        @Override
        public void onSignInFailed() {
            hello.setText(getString(R.string.signed_out_greeting));
            signInBar.setVisibility(View.VISIBLE);
            signOutBar.setVisibility(View.GONE);
        }

        @Override
        public void onSignInSucceeded() {

            signInBar.setVisibility(View.GONE);
            signOutBar.setVisibility(View.VISIBLE);
             // Set the greeting appropriately on main menu
            Player p = Games.Players.getCurrentPlayer(getApiClient());
            String displayName;
            if (p == null) {
             //   Log.w(TAG, "mGamesClient.getCurrentPlayer() is NULL!");
                displayName = "";
            } else {
                displayName = p.getDisplayName();
            }
           // hello.setText("Hello, " + displayName);

                pushAccomplishments();
                Toast.makeText(this, getString(R.string.your_progress_will_be_uploaded),
                        Toast.LENGTH_LONG).show();

        }
        //check for achievements and unlock the appropriate ones
         void checkForAchievements() {
                // Check if each condition is met; if so, unlock the corresponding
                // achievement.
              bestTimeInSeconds = loadGameBestTimeSec();
              if(bestTimeInSeconds >= 900){ //15 minutes
                  survivor = true;
                  tribalWarriror = true;
              }

            }

          void pushAccomplishments() {
              if (survivor) 
                    Games.Achievements.unlock(getApiClient(), getString(R.string.achievement_survivor));

              if (tribalWarriror) 
                    Games.Achievements.unlock(getApiClient(), getString(R.string.achievement_tribal_warrior));


              if(bestTimeInSeconds >= 60){ //1 minute atleast
                     bestTimeInMinutes = (int)bestTimeInSeconds/60;
              Games.Leaderboards.submitScore(getApiClient(), getString(R.string.leaderboard_best_time_minutes), bestTimeInMinutes);
                }

              if(bestTimeInSeconds >= 10){   // 1 meter atleast
                    int bestDistance = (int)bestTimeInSeconds/10;
              Games.Leaderboards.submitScore(getApiClient(), getString(R.string.leaderboard_best_distance_meters), bestDistance);
                }


              Games.Leaderboards.submitScore(getApiClient(), getString(R.string.leaderboard_top_score_points), hS);

            }


             @Override


             //loading scores and achievements
             private int loadScores() {
                // TODO Auto-generated method stub
                 int score = 0;
                   try{
                    preferences = new SecurePreferences(getApplicationContext(),
                            "besiPreferences", "1234", true);
                    score = Integer.parseInt(preferences.getString("highScore"));
                   }catch(Exception e){}
                    return score;

                    }

             private float loadGameBestTimeSec() {
                 float time = 0;
                  try{
                preferences = new SecurePreferences(getApplicationContext(),
                            "besiPreferences", "1234", true);
                time = Float.parseFloat(preferences.getString("gameTimeSec"));
                  }catch(Exception e){}
                   return time;
             }

             private int loadCalabashesCompleted() {
                    try{
                        preferences = new SecurePreferences(getApplicationContext(),
                                "makolaPref", "1234", true);
                        return Integer.parseInt(preferences.getString("bookCompleted")== null ? "0" : preferences.getString("bookCompleted"));
                       }catch(Exception e){
                         return 0;  
                       }
                }

             private int loadLevelCompleted() {
                    try{
                        preferences = new SecurePreferences(getApplicationContext(),
                                "makolaPref", "1234", true);
                        return Integer.parseInt(preferences.getString("levelCompleted")== null ? "0" : preferences.getString("levelCompleted"));
                       }catch(Exception e){
                         return 0;  
                       }
                }
    }