如何仅在用户登录时执行此代码

How to execute this code only when user signed in

我一直在尝试添加此代码以在游戏结束后更新玩家的分数,当用户登录时它按我想要的方式工作,但如果用户未登录,游戏会崩溃

void game_over() {
    num_lifes = 0;
    findViewById(R.id.hero).setEnabled(false);
    findViewById(R.id.btn_play).setVisibility(View.GONE);
    show_lifes();
    Games.getLeaderboardsClient(this, GoogleSignIn.getLastSignedInAccount(this))
            .submitScore(getString(R.string.leaderboard_id), score);

    findViewById(R.id.game_over).setVisibility(View.VISIBLE);

假设您的 User 实例中有一个函数或便捷方法来检查登录,您只需使用

void game_over() {
    if (isSignedIn) {
        num_lifes = 0;
        findViewById(R.id.hero).setEnabled(false);
        findViewById(R.id.btn_play).setVisibility(View.GONE);
        show_lifes();
        Games.getLeaderboardsClient(this, GoogleSignIn.getLastSignedInAccount(this))
            .submitScore(getString(R.string.leaderboard_id), score);

        findViewById(R.id.game_over).setVisibility(View.VISIBLE);
    }
}

你的 isSignedIn 方法看起来像这样

private boolean isSignedIn() {
  return GoogleSignIn.getLastSignedInAccount(context) != null;
}