Android GPS - 向排行榜提交高分

标签 android google-play-services google-play-games

我正在尝试向我的排行榜提交高分,但由于某种原因它不起作用。应用程序不会崩溃,logcat 中也没有错误。

当用户未登录时,将弹出 Google Play 游戏。目前,当用户获得新的高分时,应用程序会自动显示 toast 。所以我的 Asynctask 似乎没有正确编码?

public class result extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks{

public GoogleApiClient mGoogleApiClient;
private static int RC_SIGN_IN = 9001;
private boolean mResolvingConnectionFailure = false;
private boolean mAutoStartSignInFlow = true;
private boolean mSignInClicked = false;

public int HighScore;

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

    // Create the Google Api Client with access to the Play Games services
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(Games.API).addScope(Games.SCOPE_GAMES)
            // add other APIs and scopes here as needed
            .build();

    TextView scoreLabel = (TextView) findViewById(R.id.scoreLabel);
    TextView highScoreLabel = (TextView) findViewById(R.id.highScoreLabel);

    int score = getIntent().getIntExtra("SCORE", 0);
    scoreLabel.setText(score + "");

    SharedPreferences settings = getSharedPreferences("HIGH_SCORE", Context.MODE_PRIVATE);
    HighScore = settings.getInt("HIGH_SCORE", 0);

    if (score > HighScore) {
        highScoreLabel.setText("High Score : " + score);
        submitScore(score);
        // Update High Score
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt("HIGH_SCORE", score);
        editor.commit();

    } else {
        highScoreLabel.setText("High Score : " + HighScore);
    }

}

public void tryAgain(View view) {
    startActivity(new Intent(getApplicationContext(), start.class));
}


// Disable Return Button
@Override
public boolean dispatchKeyEvent(KeyEvent event) {

    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (event.getKeyCode()) {
            case KeyEvent.KEYCODE_BACK:
                return true;
        }
    }

    return super.dispatchKeyEvent(event);
}

public class LoadData extends AsyncTask<Void, Void, Void> {

    ProgressDialog pdLoading = new ProgressDialog(result.this);
    //declare other objects as per your need

    @Override
    protected void onPreExecute()
    {
        pdLoading.setMessage("\tSending highscore to leaderboard...");
        pdLoading.show();

        //do initialization of required objects objects here
    };
    @Override
    protected Void doInBackground(Void... params)
    {
        Games.Leaderboards.submitScoreImmediate(mGoogleApiClient, getString(R.string.leaderboard_top_players), HighScore);
        //do loading operation here
        return null;
    }
    @Override
    protected void onPostExecute(Void result)
    {
        super.onPostExecute(result);
        pdLoading.dismiss();
    };
}

//Start GPS
@Override
public void onConnected(@Nullable Bundle bundle) {

}

@Override
public void onConnectionSuspended(int i) {
    // Attempt to reconnect
    mGoogleApiClient.connect();
}

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

    // If the sign in button was clicked or if auto sign-in is enabled,
    // launch the sign-in flow
    if (mSignInClicked || mAutoStartSignInFlow) {
        mAutoStartSignInFlow = false;
        mSignInClicked = false;
        mResolvingConnectionFailure = true;

        // Attempt to resolve the connection failure using BaseGameUtils.
        // The R.string.signin_other_error value should reference a generic
        // error string in your strings.xml file, such as "There was
        // an issue with sign in, please try again later."
        if (!BaseGameUtils.resolveConnectionFailure(this,
                mGoogleApiClient, connectionResult,
                RC_SIGN_IN, getString(R.string.signin_other_error))) {
            mResolvingConnectionFailure = false;
        }
    }

    // Put code here to display the sign-in button
}

public void submitScore(long highscore){
    if (mGoogleApiClient.isConnected()){
        LoadData task = new LoadData();
        task.execute();
        //Games.Leaderboards.submitScoreImmediate(mGoogleApiClient, getString(R.string.leaderboard_top_players), highscore);
    }else{
        Toast.makeText(this, "Unable to submit highscore", Toast.LENGTH_SHORT).show();
    }
}

@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

@Override
protected void onStop() {
    super.onStop();
    mGoogleApiClient.disconnect();
}

protected void onActivityResult(int requestCode, int resultCode,
                                Intent intent) {
    if (requestCode == RC_SIGN_IN) {
        mSignInClicked = false;
        mResolvingConnectionFailure = false;
        if (resultCode == RESULT_OK) {
            mGoogleApiClient.connect();
        } else {
            // Bring up an error dialog to alert the user that sign-in
            // failed. The R.string.signin_failure should reference an error
            // string in your strings.xml file that tells the user they
            // could not be signed in, such as "Unable to sign in."
            BaseGameUtils.showActivityResultError(this,
                    requestCode, resultCode, R.string.signin_failure);
        }
    }
}
}

最佳答案

您似乎在声明 mGoogleAPIClient 但实际上并没有创建它的实例,因此出现了“NullPointerException”

在尝试使用 mGoogleAPIClient 之前,添加以下内容来创建它......

mGoogleApiClient = new GoogleApiClient.Builder(this)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .addApi(Games.API).addScope(Games.SCOPE_GAMES)
    // add other APIs and scopes here as needed
    .build();

参见 Here了解更多详情

希望对你有帮助

关于Android GPS - 向排行榜提交高分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40808832/

相关文章:

android - 显示成就UI();不想出现在 Android 上

安卓每秒帧数

android - 引用 google-play-services 库

android - Google Plus 从 Android 应用分享

android - PublisherAdView.loadAd() 抛出 SecurityException - getTasks() 需要 android.permission.GET_TASKS

android - 从 fragment 调用 Google Play 游戏服务

android - libGDX Google Play 游戏服务 - Android

java - 当 android 设备处于 wifi 时,SSLSocket 在 getInputStream 处挂起

android - 如何防止相同的图像重复自身?

android - 操作栏背景颜色?- Play Newstand 应用