I'm trying to submit a highscore to my leaderboards, but for some reason it doesn't work. The app doesn't crash and there is no error in the logcat.
When the user isn't logged in there will be a pop-up of Google Play Games. Currently when a user gets a new highscore the app automatically shows the toast. So it seems my Asynctask is not correctly coded?
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);
}
}
}
}
You seem to be declaring mGoogleAPIClient but not actually creating an instance of it, hence your 'NullPointerException'
Before you try to use mGoogleAPIClient, add the following to create it.....
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();
See Here for more details
Hope this helps
Related
This is my code
public class gsign extends Activity implements ConnectionCallbacks,OnConnectionFailedListener {
private static final int RC_SIGN_IN = 0;
private static final String TAG = "MainActivity";
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Plus.API)
.addConnectionCallbacks(this).addOnConnectionFailedListener(this)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
protected void onStart() {
super.onStart();
signInWithGplus();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
mConnectionResult = result;
if (mSignInClicked) {
resolveSignInError();
}
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
// Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
getProfileInformation();
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
else
getProfileInformation();
}
/**
* Method to resolve any signin errors
* */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
}
I also have code to register the user in my cloud backend and to fetch their information but I am getting the following error
Caused by: java.lang.NullPointerException
at com.example.nirmal.loginpage.gsign.resolveSignInError(gsign.java:127)
at com.example.nirmal.loginpage.gsign.signInWithGplus(gsign.java:117)
at com.example.nirmal.loginpage.gsign.onCreate(gsign.java:56)
The following error points to if (mConnectionResult.hasResolution())
Normally this error may be caused while calling signInWithGPlus() from the onCreate() method but even after calling it from onStart() I got the same error.
The problem is I used the same code in another app(in fact I copied from that one) in which it ran perfectly so I have no idea what caused this error.
I also created separate OAuth client key for this app. So can anyone point me to where I am going wrong????
The stack trace tells it all...
You don't call mGoogleApiClient.connect() until onStart(). Meanwhile back in onCreate(), which is called before onStart(), you call the signInWithGplus(); method.
!mGoogleApiClient.isConnecting() in that method is true leading to resolveSignInError() being called.
You have not yet assigned a value to mConnectionResult so calling mConnectionResult.hasResolution() in resolveSignInError() will throw a NullPointerException.
I am trying to let the user login in my app with his google account.
I setup the client id in the google developer console, with the package name and the sha1 of my debug keystore, enabled the google plus api and filled in the consent screen.
Here is the code of the activity which perform the login with googleApiClient:
public class IntroActivity extends BaseActivity implements
LoginFragment.FragmentListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final int RC_GOOGLE_SIGN_IN = 0;
private GoogleApiClient googleApiClient;
private boolean intentInProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
if (savedInstanceState == null) {
LoginFragment loginFragment = new LoginFragment();
replaceFragment(loginFragment, false);
}
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API, Plus.PlusOptions.builder().build())
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build();
}
#Override
protected void onStop() {
super.onStop();
if (googleApiClient.isConnected()) {
googleApiClient.disconnect();
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
switch (requestCode) {
case RC_GOOGLE_SIGN_IN:
intentInProgress = false;
if (!googleApiClient.isConnecting()) {
googleApiClient.connect();
}
break;
}
}
#Override
public void onGoogleSignInClick() {
googleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
if (Plus.PeopleApi.getCurrentPerson(googleApiClient) != null) {
String email = Plus.AccountApi.getAccountName(googleApiClient);
String token = null;
try {
token = GoogleAuthUtil.getToken(this, email, Plus.SCOPE_PLUS_LOGIN.toString());
} catch (IOException | GoogleAuthException e) {
e.printStackTrace();
}
showShortToast(token);
}
}
#Override
public void onConnectionSuspended(int i) {
googleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (!intentInProgress && connectionResult.hasResolution()) {
try {
intentInProgress = true;
startIntentSenderForResult(connectionResult.getResolution().getIntentSender(), RC_GOOGLE_SIGN_IN, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
intentInProgress = false;
googleApiClient.connect();
}
} else {
showShortToast("onConnectionFailed");
}
}
}
As soon as the googleApiClient starts connecting, it fails to connect and it displays a popup in order to choose the account. Once selected, it still goes in onConnectionFailed method, but this time seems there is no resolution for the problem.
The ConnectionResult get {statusCode=SIGN_IN_FAILED, resolution=null}
Why I get sign in failed? Is it possible that the app is not linked with the project on the dev console somehow?
I'm trying to carry out the Google Plus login within my app but no matter what I do, if the Scope is set to Plus.SCOPE_PLUS_LOGIN, I always get a ConnectionResult whose ErrorCode is 17 (SIGN_IN_FAILED). On the other hand, if I pick Plus.SCOPE_PLUS_PROFILE the app gets connected but when I retrieve the Person object, this one is always null.
I have created a new project in the developer console, enable the Google+ API and created a Cliend ID that includes the proper SHA1 fingerprint for the debug version of the app and its package. I have also picked an email and product name.
I have also tried to rename the package of the app and update the project in the developer console, but I still get the same error.
The thing is that I have downloaded the Google example, created a project in my developer console for it and it works... but when I try to use the same class that does the job in my app, it always fails... really weird. I have also checked the Google + API usage section and it never handles any request sent by my app... whereas it does it for the Google example...
This is the code of the class that carries out the whole process.. as you can see it looks practically the same as the one in the Google example...
public class MainActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
ResultCallback<People.LoadPeopleResult>, View.OnClickListener {
private static final int STATE_DEFAULT = 0;
private static final int STATE_SIGN_IN = 1;
private static final int STATE_IN_PROGRESS = 2;
private static final int RC_SIGN_IN = 0;
private static final int DIALOG_PLAY_SERVICES_ERROR = 0;
private static final String SAVED_PROGRESS = "sign_in_progress";
private int mSignInError;
private SignInButton mSignInButton;
private Button mSignOutButton;
private Button mRevokeButton;
private TextView mStatus;
private ListView mCirclesListView;
private ArrayAdapter<String> mCirclesAdapter;
private ArrayList<String> mCirclesList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
mSignOutButton = (Button) findViewById(R.id.sign_out_button);
mRevokeButton = (Button) findViewById(R.id.revoke_access_button);
mStatus = (TextView) findViewById(R.id.sign_in_status);
mCirclesListView = (ListView) findViewById(R.id.circles_list);
mSignInButton.setOnClickListener(this);
mSignOutButton.setOnClickListener(this);
mRevokeButton.setOnClickListener(this);
mCirclesList = new ArrayList<String>();
mCirclesAdapter = new ArrayAdapter<String>(
this, R.layout.circle_member, mCirclesList);
mCirclesListView.setAdapter(mCirclesAdapter);
if (savedInstanceState != null) {
mSignInProgress = savedInstanceState
.getInt(SAVED_PROGRESS, STATE_DEFAULT);
}
mGoogleApiClient = buildGoogleApiClient();
}
private GoogleApiClient buildGoogleApiClient() {
return new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API, Plus.PlusOptions.builder().build())
//.addScope(Plus.SCOPE_PLUS_PROFILE)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(SAVED_PROGRESS, mSignInProgress);
}
#Override
public void onClick(View v) {
if (!mGoogleApiClient.isConnecting()) {
switch (v.getId()) {
case R.id.sign_in_button:
mStatus.setText("Sign in");
resolveSignInError();
break;
case R.id.sign_out_button:
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
break;
case R.id.revoke_access_button:
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient);
mGoogleApiClient = buildGoogleApiClient();
mGoogleApiClient.connect();
break;
}
}
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "onConnected");
mSignInButton.setEnabled(false);
mSignOutButton.setEnabled(true);
mRevokeButton.setEnabled(true);
Person currentUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
Log.d("profile", "profile, name: " + currentUser.getName() + ", id: " + currentUser.getId());
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
mStatus.setText(String.format("Sign in",
email));
Plus.PeopleApi.loadVisible(mGoogleApiClient, null)
.setResultCallback(this);
mSignInProgress = STATE_DEFAULT;
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "onConnectionFailed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
if (result.getErrorCode() == ConnectionResult.API_UNAVAILABLE) {
} else if (mSignInProgress != STATE_IN_PROGRESS) {
mSignInIntent = result.getResolution();
mSignInError = result.getErrorCode();
if (mSignInProgress == STATE_SIGN_IN) {
resolveSignInError();
}
}
onSignedOut();
}
private void resolveSignInError() {
if (mSignInIntent != null) {
try {
mSignInProgress = STATE_IN_PROGRESS;
startIntentSenderForResult(mSignInIntent.getIntentSender(),
RC_SIGN_IN, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.i(TAG, "Sign in intent could not be sent: "
+ e.getLocalizedMessage());
mSignInProgress = STATE_SIGN_IN;
mGoogleApiClient.connect();
}
} else {
showDialog(DIALOG_PLAY_SERVICES_ERROR);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
switch (requestCode) {
case RC_SIGN_IN:
if (resultCode == RESULT_OK) {
mSignInProgress = STATE_SIGN_IN;
} else {
mSignInProgress = STATE_DEFAULT;
}
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
break;
}
}
#Override
public void onResult(People.LoadPeopleResult peopleData) {
if (peopleData.getStatus().getStatusCode() == CommonStatusCodes.SUCCESS) {
mCirclesList.clear();
PersonBuffer personBuffer = peopleData.getPersonBuffer();
try {
int count = personBuffer.getCount();
for (int i = 0; i < count; i++) {
mCirclesList.add(personBuffer.get(i).getDisplayName());
}
} finally {
personBuffer.close();
}
mCirclesAdapter.notifyDataSetChanged();
} else {
Log.e(TAG, "Error requesting visible circles: " + peopleData.getStatus());
}
}
private void onSignedOut() {
mSignInButton.setEnabled(true);
mSignOutButton.setEnabled(false);
mRevokeButton.setEnabled(false);
mStatus.setText("Sign out");
mCirclesList.clear();
mCirclesAdapter.notifyDataSetChanged();
}
#Override
public void onConnectionSuspended(int cause) {
ConnectionResult that we can attempt to resolve.
mGoogleApiClient.connect();
}
I implemented Google Play Games sign in in my app, and it works.
But I have problem when I try to use app in offline mode, without Internet connection, because it ask me again to sign in.
It seems like sign in session expired or something like that, because this happens 30 minutes or 1 hour after successful sign in.
Here is my code:
public class MainActivity extends Activity implements MainMenuFragment.Listener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
GameFragment.Listener, ResultFragment.Listener {
//Fragments
MainMenuFragment mMainFragment;
GameFragment mGameFragment;
ResultFragment mResultFragment;
// Client used to interact with Google APIs
private GoogleApiClient mGoogleApiClient;
// Are we currently resolving a connection failure?
private boolean mResolvingConnectionFailure = false;
// Has the user clicked the sign-in button?
private boolean mSignInClicked = false;
// Automatically start the sign-in flow when the Activity starts
private boolean mAutoStartSignInFlow = true;
// request codes we use when invoking an external activity
private static final int RC_RESOLVE = 5000;
private static final int RC_UNUSED = 5001;
private static final int RC_SIGN_IN = 9001;
//Debug
private String TAG = "IGRA";
//Shared Preferences stuff
private SharedPreferences mPrefs;
public static final String PREFS_NAME = "TheButtonChallenge";
private SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set activity to be the full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
// Create the Google API Client with access to Plus and Games
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API).addScope(Plus.SCOPE_PLUS_LOGIN)
.addApi(Games.API).addScope(Games.SCOPE_GAMES)
.build();
Log.d(TAG, "activity on created");
//Fragments
mMainFragment = new MainMenuFragment();
mGameFragment = new GameFragment();
mResultFragment = new ResultFragment();
// listen to fragment events
mMainFragment.setListener(this);
mGameFragment.setListener(this);
mResultFragment.setListener(this);
// add initial fragment (welcome fragment)
if (savedInstanceState == null) {
Log.d(TAG, "activity on created savedInstanceState");
getFragmentManager().beginTransaction().add(R.id.container, mMainFragment).commit();
}
mPrefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
editor = mPrefs.edit();
}
// Switch UI to the given fragment
void switchToFragment(Fragment newFrag) {
Log.d(TAG, "switch fragment");
getFragmentManager().beginTransaction().replace(R.id.container, newFrag)
.commitAllowingStateLoss();
}
private boolean isSignedIn() {
return (mGoogleApiClient != null && mGoogleApiClient.isConnected());
}
#Override
protected void onStart() {
super.onStart();
if(!isSignedIn()) {
Log.d(TAG, "onStart(): connecting");
mGoogleApiClient.connect();
}
else{
}
}
#Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop(): disconnecting");
/*if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}*/
}
#Override
public void onStartGameRequested() {
Log.d(TAG, "new game");
startGame();
}
#Override
public void onShowAchievementsRequested() {
if (isSignedIn()) {
startActivityForResult(Games.Achievements.getAchievementsIntent(mGoogleApiClient),
RC_UNUSED);
} else {
BaseGameUtils.makeSimpleDialog(this, getString(R.string.achievements_not_available)).show();
}
}
#Override
public void onShowLeaderboardsRequested() {
if (isSignedIn()) {
startActivityForResult(Games.Leaderboards.getAllLeaderboardsIntent(mGoogleApiClient),
RC_UNUSED);
} else {
BaseGameUtils.makeSimpleDialog(this, getString(R.string.leaderboards_not_available)).show();
}
}
#Override
public int getHighScore() {
return mPrefs.getInt("highScore", 0);
}
void startGame(){
switchToFragment(mGameFragment);
}
public void onEnteredScore(int finalScore){
mResultFragment.setFinalScore(finalScore);
// push those accomplishments to the cloud, if signed in
pushAccomplishments(finalScore);
// check for achievements
checkForAchievements(finalScore);
// switch to the exciting "you won" screen
switchToFragment(mResultFragment);
}
/**
* Check for achievements and unlock the appropriate ones.
*
* #param finalScore the score the user got.
*/
void checkForAchievements(int finalScore) {
int playCounter = mPrefs.getInt("playCounter", 0);
int highScore = mPrefs.getInt("highScore", 0);
playCounter++;
Log.d("FINAL SCORE:" , String.valueOf(finalScore));
Log.d("HIGH SCORE: ", String.valueOf(highScore));
editor.putInt("playCounter", playCounter);
editor.commit();
if(finalScore>highScore){
editor.putInt("highScore", finalScore);
editor.commit();
mResultFragment.setHighScore(finalScore);
}
if(playCounter == 1){
Games.Achievements.unlock(mGoogleApiClient, getString(R.string.achievement_first_time_play));
}
// Check if each condition is met; if so, unlock the corresponding
// achievement.
if (finalScore >= 50) {
//achievementToast(getString(R.string.achievement_arrogant_toast_text));
Games.Achievements.unlock(mGoogleApiClient, getString(R.string.achievement_win_50_points));
}
if (finalScore >= 80) {
Games.Achievements.unlock(mGoogleApiClient, getString(R.string.achievement_win_80_points));
}
if (finalScore >= 100) {
// achievementToast(getString(R.string.achievement_leet_toast_text));
Games.Achievements.unlock(mGoogleApiClient, getString(R.string.achievement_win_100_points));
}
if(finalScore >= 150){
Games.Achievements.unlock(mGoogleApiClient, getString(R.string.achievement_win_150_points));
}
if(finalScore >= 200){
Games.Achievements.unlock(mGoogleApiClient, getString(R.string.achievement_win_200_points));
}
}
void achievementToast(String achievement) {
// Only show toast if not signed in. If signed in, the standard Google Play
// toasts will appear, so we don't need to show our own.
if (!isSignedIn()) {
Toast.makeText(this, getString(R.string.achievement) + ": " + achievement,
Toast.LENGTH_LONG).show();
}
}
private void pushAccomplishments(int finalScore) {
if (!isSignedIn()) {
// can't push to the cloud, so save locally
// mOutbox.saveLocal(this);
Log.d(TAG, "can't push to the cloud, so save locally");
return;
}
Games.Leaderboards.submitScore(mGoogleApiClient, getString(R.string.number_guesses_leaderboard),
finalScore);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected(): connected to Google APIs");
// Show sign-out button on main menu
//mMainFragment.setShowSignInButton(false);
// Show "you are signed in" message on win screen, with no sign in button.
//mWinFragment.setShowSignInButton(false);
// Set the greeting appropriately on main menu
Player p = Games.Players.getCurrentPlayer(mGoogleApiClient);
String displayName;
if (p == null) {
Log.w(TAG, "mGamesClient.getCurrentPlayer() is NULL!");
displayName = "???";
} else {
displayName = p.getDisplayName();
Log.d(TAG, displayName);
}
mMainFragment.setGreeting("Hello, " + displayName);
// if we have accomplishments to push, push them
/*if (!mOutbox.isEmpty()) {
pushAccomplishments();
Toast.makeText(this, getString(R.string.your_progress_will_be_uploaded),
Toast.LENGTH_LONG).show();
}*/
}
#Override
public void onWinScreenDismissed() {
switchToFragment(mGameFragment);
}
#Override
public void onWinScreenSignInClicked() {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == RC_SIGN_IN) {
mSignInClicked = false;
mResolvingConnectionFailure = false;
if (resultCode == RESULT_OK) {
mGoogleApiClient.connect();
} else {
BaseGameUtils.showActivityResultError(this, requestCode, resultCode,
R.string.signin_failure, R.string.signin_other_error);
}
}
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "onConnectionSuspended(): attempting to connect");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed(): attempting to resolve");
if (mResolvingConnectionFailure) {
Log.d(TAG, "onConnectionFailed(): already resolving");
return;
}
if (mSignInClicked || mAutoStartSignInFlow) {
mAutoStartSignInFlow = false;
mSignInClicked = false;
mResolvingConnectionFailure = true;
// if (Utils.isConnected(getApplicationContext())) {
if (!BaseGameUtils.resolveConnectionFailure(this, mGoogleApiClient, connectionResult,
RC_SIGN_IN, getString(R.string.signin_other_error))) {
mResolvingConnectionFailure = false;
}
//}
//else{
// Log.d("IGRA", "Nema Interenta");
// }
}
// Sign-in failed, so show sign-in button on main menu
mMainFragment.setGreeting(getString(R.string.signed_out_greeting));
//mMainMenuFragment.setShowSignInButton(true);
// mWinFragment.setShowSignInButton(true);
}
Currently I have 3 activities in my application. The first activity is to load default Splashscreen.class, I would like this activity to check whether the user accessed with your Google+ account "Sign In" on Login.class class.
In short, La Splashscreen.class class to check if the user logged in or not and direct it to one activity or another. I leave my code.
Splashscreen.class
public class SplashScreen extends Activity {
private boolean mIsBackButtonPressed;
private static final int SPLASH_DURATION = 2500;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
finish();
if (!mIsBackButtonPressed) {
/*if(){ If the user is connected go to class Mainactivity.class
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
SplashScreen.this.startActivity(intent);
}
}else{
//If the user is not connected go to class Login.class
Intent intent = new Intent(SplashScreen.this, Login.class);
SplashScreen.this.startActivity(intent);
}
*/
}
}, SPLASH_DURATION);
}
#Override
public void onBackPressed() {
mIsBackButtonPressed = true;
super.onBackPressed();
}
}
Login.class
public class Login extends Activity implements OnPageChangeListener,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, View.OnClickListener{
/* Request code used to invoke sign in user interactions. */
private static final int RC_SIGN_IN = 0;
static Context context;
/* Client used to interact with Google APIs. */
private static GoogleApiClient mGoogleApiClient;
/* A flag indicating that a PendingIntent is in progress and prevents
* us from starting further intents.
*/
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
boolean result_back;
private ViewPager vp;
private ViewPagerAdapter vpAdapter;
private List<View> views;
private ProgressDialog pDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
initViews();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build();
pDialog = new ProgressDialog(this);
pDialog.setMessage("Conectando ...");
findViewById(R.id.btn_sign_in).setOnClickListener(this);
}
public void onClick(View view) {
pDialog.show();
if (view.getId() == R.id.btn_sign_in
&& !mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
public void onConnectionFailed(ConnectionResult result) {
if (!mIntentInProgress) {
// Store the ConnectionResult so that we can use it later when the user clicks
// 'sign-in'.
mConnectionResult = result;
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
public void onConnected(Bundle connectionHint) {
// We've resolved any connection errors. mGoogleApiClient can be used to
// access Google APIs on behalf of the user.
pDialog.dismiss();
mSignInClicked = false;
//Toast.makeText(this, "User is connected!", Toast.LENGTH_SHORT).show();
getProfileInformation();
Intent i=new Intent(Login.this, MainActivity.class);
startActivity(i);
}
/**
* Fetching user's information name, email, profile pic
* */
public static void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
currentPerson.getImage().getUrl();
currentPerson.getUrl();
Plus.AccountApi.getAccountName(mGoogleApiClient);
Toast.makeText(context,"Name: " + personName,Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context,
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
}
private void resolveSignInError() {
if(mConnectionResult == null){
Toast.makeText(getApplicationContext(), "Es null", Toast.LENGTH_SHORT).show();
}else{
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
startIntentSenderForResult(mConnectionResult.getResolution().getIntentSender(),
RC_SIGN_IN, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
// The intent was canceled before it was sent. Return to the default
// state and attempt to connect to get an updated ConnectionResult.
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
}
private void initViews() {
LayoutInflater inflater = LayoutInflater.from(this);
views = new ArrayList<View>();
views.add(inflater.inflate(R.layout.layout_one, null));
views.add(inflater.inflate(R.layout.layout_two, null));
views.add(inflater.inflate(R.layout.layout_three, null));
vpAdapter = new ViewPagerAdapter(views, this);
vp = (ViewPager) findViewById(R.id.pager);
vp.setAdapter(vpAdapter);
vp.setOnPageChangeListener(this);
CirclePageIndicator indicator = (CirclePageIndicator)findViewById(R.id.circle);
indicator.setViewPager(vp);
indicator.setSnap(true);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int arg0) {
}
}
Thank you all, Greetings!