【问题标题】:How do I implement Google Play Game services in my app in Android Studio?如何在 Android Studio 的应用中实现 Google Play 游戏服务?
【发布时间】:2015-03-05 21:04:19
【问题描述】:

我正试图弄清楚如何在我的应用中实现 Google Play 游戏服务。在 Google Play 开发者控制台上,我使用 SHA1 密钥将游戏与相关应用程序相关联,并且我知道如何在此处添加排行榜和成就。我还在 Android Studio 中安装了 Google Play 服务和 Google 存储库,并将依赖项添加到 build.gradle(如此处所述:http://developer.android.com/google/play-services/setup.html)但我不确定 如何在该页面上执行最后两个步骤(创建 Proguard 异常并确保设备具有 Google Play 服务 APK)以及是否有必要 - 后者甚至 Google Play 游戏示例项目似乎都没有。

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

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

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

【问题讨论】:

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


    【解决方案1】:

    您应该使用 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;  
                           }
                    }
        }
    

    【讨论】:

    • 好的,谢谢,有点道理,我还需要其他代码吗,比如 BaseGameUtils?我是否需要检查设备是否安装了 Google Play 游戏服务等?
    • 是的,你需要 BaseGameUitls 库-developers.google.com/games/services/downloads 不,你不需要检查设备是否安装了 google play 游戏服务
    猜你喜欢
    • 1970-01-01
    • 2016-01-04
    • 2015-07-11
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 2022-12-28
    • 2018-06-15
    • 2014-04-17
    相关资源
    最近更新 更多