I have successfully implemented google plus
list people activity
public class ListPeopleActivity extends Activity implements
PlusClient.ConnectionCallbacks, PlusClient.OnPeopleLoadedListener,
PlusClient.OnConnectionFailedListener, DialogInterface.OnCancelListener {
private static final String TAG = "ListPeopleActivity";
private static final String STATE_RESOLVING_ERROR = "resolving_error";
private static final int DIALOG_GET_GOOGLE_PLAY_SERVICES = 1;
private static final int REQUEST_CODE_SIGN_IN = 1;
private static final int REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES = 2;
private ArrayAdapter mListAdapter;
private ListView mPersonListView;
private ArrayList<String> mListItems;
private PlusClient mPlusClient;
private boolean mResolvingError;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.person_list_activity);
mPlusClient = new PlusClient.Builder(this, this, this)
.setVisibleActivities(MomentUtil.VISIBLE_ACTIVITIES).build();
mListItems = new ArrayList<String>();
mListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mListItems);
mPersonListView = (ListView) findViewById(R.id.person_list);
mResolvingError = savedInstanceState != null
&& savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false);
int available = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (available != ConnectionResult.SUCCESS) {
showDialog(DIALOG_GET_GOOGLE_PLAY_SERVICES);
}
}
#Override
protected Dialog onCreateDialog(int id) {
if (id != DIALOG_GET_GOOGLE_PLAY_SERVICES) {
return super.onCreateDialog(id);
}
int available = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (available == ConnectionResult.SUCCESS) {
return null;
}
if (GooglePlayServicesUtil.isUserRecoverableError(available)) {
return GooglePlayServicesUtil.getErrorDialog(available, this,
REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES, this);
}
return new AlertDialog.Builder(this)
.setMessage(R.string.plus_generic_error).setCancelable(true)
.setOnCancelListener(this).create();
}
#Override
protected void onStart() {
super.onStart();
mPlusClient.connect();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError);
}
#Override
protected void onStop() {
super.onStop();
mPlusClient.disconnect();
}
#Override
public void onPeopleLoaded(ConnectionResult status,
PersonBuffer personBuffer, String nextPageToken) {
switch (status.getErrorCode()) {
case ConnectionResult.SUCCESS:
mListItems.clear();
try {
int count = personBuffer.getCount();
Log.e("", "count : " + count);
for (int i = 0; i < count; i++) {
mListItems.add(personBuffer.get(i).getDisplayName());
Log.e("", "" + personBuffer.get(i).getDisplayName() + " "
+ personBuffer.get(i).getId() + " isPlusUser : "
+ personBuffer.get(i).isPlusUser()
+ " isVerified : "
+ personBuffer.get(i).isVerified()
+ " hasCircledByCount : "
+ personBuffer.get(i).hasCircledByCount()
+ " getObjectType : "
+ personBuffer.get(i).getObjectType());
}
} finally {
personBuffer.close();
}
mListAdapter.notifyDataSetChanged();
break;
case ConnectionResult.SIGN_IN_REQUIRED:
mPlusClient.disconnect();
mPlusClient.connect();
break;
default:
Log.e(TAG, "Error when listing people: " + status);
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE_SIGN_IN:
mResolvingError = false;
handleResult(resultCode);
break;
case REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES:
handleResult(resultCode);
break;
}
}
private void handleResult(int resultCode) {
if (resultCode == RESULT_OK) {
// onActivityResult is called after onStart (but onStart is not
// guaranteed to be called while signing in), so we should make
// sure we're not already connecting before we call connect again.
if (!mPlusClient.isConnecting() && !mPlusClient.isConnected()) {
mPlusClient.connect();
}
} else {
Log.e(TAG, "Unable to sign the user in.");
finish();
}
}
#Override
public void onConnected(Bundle connectionHint) {
mPersonListView.setAdapter(mListAdapter);
// mPlusClient.loadVisiblePeople(this, null);
mPlusClient.loadPeople(this, "103193341800315457743");
}
#Override
public void onDisconnected() {
mPersonListView.setAdapter(null);
mPlusClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mResolvingError) {
return;
}
mPersonListView.setAdapter(null);
try {
result.startResolutionForResult(this, REQUEST_CODE_SIGN_IN);
mResolvingError = true;
} catch (IntentSender.SendIntentException e) {
// Get another pending intent to run.
mPlusClient.connect();
}
}
#Override
public void onCancel(DialogInterface dialogInterface) {
Log.e(TAG, "Unable to sign the user in.");
finish();
}
In above code it mPlusClient.loadVisiblePeople(this, null); load all visible(in circle) people.. I want to load one specific people which is in my circle. and mPlusClient.loadPeople(this, "103193341800315457743"); this can load specific people but how can I know it is in my circle or not... because it returns everytime whether it is in my circle or not.
Actually I want to know that specific people is in my circle or not.
try, mPlusClient.loadPerson(this, "103193341800315457743");
Related
See code below. Pocketsphinx is configured with a keyphrase search to trigger on the word "record". Searching is then started, and talking causes onBeginningOfSpeech and onEndOfSpeech to be called, but no other listener methods get called, whatever I say.
public class MainActivity extends AppCompatActivity implements RecognitionListener {
private final Handler handler = new Handler ();
private SpeechRecognizer recognizer;
private final static String KEYWORD = "record";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
makeButtonStartButton ();
ensureRecordAudioPermission ();
startKeywordListener ();
}
private void startKeywordListener() {
// Recognizer initialization is a time-consuming and it involves IO,
// so we execute it in async task
new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(MainActivity.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception result) {
if (result != null) {
Log.e("MainActivity", "Failed to init recognizer " + result);
} else {
startKeywordSearch ();
}
}
}.execute();
}
private void startKeywordSearch() {
Log.i("MainActivity", "Starting keyword search: " + KEYWORD);
recognizer.stop();
recognizer.startListening(KEYWORD);
}
private void setupRecognizer(File assetsDir) throws IOException {
// The recognizer can be configured to perform multiple searches
// of different kind and switch between them
recognizer = SpeechRecognizerSetup.defaultSetup()
.setAcousticModel(new File(assetsDir, "en-us-ptm"))
.setDictionary(new File(assetsDir, "cmudict-en-us.dict"))
.setRawLogDir(assetsDir) // To disable logging of raw audio comment out this call (takes a lot of space on the device)
.getRecognizer();
recognizer.addListener(this);
// Create keyword-activation search.
recognizer.addKeyphraseSearch(KEYWORD, KEYWORD);
}
private void ensureRecordAudioPermission() {
// Check if user has given permission to record audio
int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO);
if (permissionCheck == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
return;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startKeywordListener();
} else {
finish();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (recognizer != null) {
recognizer.cancel();
recognizer.shutdown();
}
}
private void makeButtonStartButton() {
findViewById(R.id.startButton).setOnClickListener(startRecording);
}
private final View.OnClickListener startRecording = new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, RecordingActivity.class));
}
};
#Override
public void onBeginningOfSpeech() {
Log.i ("MainActivity", "Beginning of speech detected");
}
#Override
public void onEndOfSpeech() {
Log.i ("MainActivity", "End of speech detected");
}
#Override
public void onPartialResult(Hypothesis hypothesis) {
if (hypothesis == null) return; // reject the null hypothesis (!)
Log.i ("MainActivity", "Partial result: " + hypothesis.getHypstr() + " (" + hypothesis.getProb() + ")");
if (hypothesis.getHypstr().equals(KEYWORD))
startRecording.onClick(null);
}
#Override
public void onResult(Hypothesis hypothesis) {
if (hypothesis == null) return; // reject the null hypothesis (!)
Log.i ("MainActivity", "Complete result: " + hypothesis.getHypstr() + " (" + hypothesis.getProb() + ")");
if (hypothesis.getHypstr().equals(KEYWORD))
startRecording.onClick(null);
}
#Override
public void onError(Exception e) {
Log.i ("MainActivity", "Error detected", e);
}
#Override
public void onTimeout() {
Log.i ("MainActivity", "Timeout occurred");
}
}
I am creating a game using the API of Google Play Games. I have read the documentation on the leaderboards. I have used the same code to update the user's score, but it always returns the code RESULT_RECONNECT_REQUIRED. I've used the logcat to display the results of the call:
E/GameProgress: Result score CgkIoY-5lt0DEAIQEA: ScoreSubmissionData{PlayerId=128090785697, StatusCode=2, TimesSpan=DAILY, Result=null, TimesSpan=WEEKLY, Result=null, TimesSpan=ALL_TIME, Result=null}
Here is the code:
public class GameActivity extends AppCompatActivity {
private GameHelper mHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
...
mHelper = new GameHelper(this, 1);
mHelper.enableDebugLog(true);
mHelper.setup(new GameHelper.GameHelperListener() {
#Override
public void onSignInFailed() {
Log.e(TAG, "Sign in failed");
}
#Override
public void onSignInSucceeded() {
Log.e(TAG, "Sign in Succeded");
addScores(GameId.LEADERBOARDS.TEN_THOUSAND);
}
});
}
private void addScores(String leaderBoard) {
PendingResult<Leaderboards.SubmitScoreResult> result = Games.Leaderboards.submitScoreImmediate(mGoogleApiClient, leaderBoard, 5);
result.setResultCallback(new ResultCallback<Leaderboards.SubmitScoreResult>() {
#Override
public void onResult(#NonNull Leaderboards.SubmitScoreResult submitScoreResult) {
Log.e(TAG, "Result score " + leaderBoard + ": " + submitScoreResult.getScoreData().toString());
}
});
}
}
GameHelperClass:
public class GameHelper implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
static final String TAG = "GameHelper";
public interface GameHelperListener {
void onSignInFailed();
void onSignInSucceeded();
}
private boolean mSetupDone = false;
private boolean mConnecting = false;
boolean mExpectingResolution = false;
boolean mSignInCancelled = false;
Activity mActivity = null;
Context mAppContext = null;
public final static int RC_RESOLVE = 9001;
final static int RC_UNUSED = 9002;
GoogleApiClient.Builder mGoogleApiClientBuilder = null;
GamesOptions mGamesApiOptions = GamesOptions.builder().build();
PlusOptions mPlusApiOptions = null;
GoogleApiClient mGoogleApiClient = null;
// Client request flags
public final static int CLIENT_NONE = 0x00;
public final static int CLIENT_GAMES = 0x01;
public final static int CLIENT_PLUS = 0x02;
public final static int CLIENT_SNAPSHOT = 0x08;
public final static int CLIENT_ALL = CLIENT_GAMES | CLIENT_PLUS
| CLIENT_SNAPSHOT;
int mRequestedClients = CLIENT_NONE;
boolean mConnectOnStart = true;
boolean mUserInitiatedSignIn = false;
ConnectionResult mConnectionResult = null;
SignInFailureReason mSignInFailureReason = null;
boolean mShowErrorDialogs = true;
boolean mDebugLog = false;
Handler mHandler;
Invitation mInvitation;
TurnBasedMatch mTurnBasedMatch;
ArrayList<GameRequest> mRequests;
// Listener
GameHelperListener mListener = null;
static final int DEFAULT_MAX_SIGN_IN_ATTEMPTS = 3;
int mMaxAutoSignInAttempts = DEFAULT_MAX_SIGN_IN_ATTEMPTS;
private GameErrorHandler mGameErrorHandler;
public GameHelper(Activity activity, int clientsToUse) {
mActivity = activity;
mAppContext = activity.getApplicationContext();
mRequestedClients = clientsToUse;
mHandler = new Handler();
}
public void setMaxAutoSignInAttempts(int max) {
mMaxAutoSignInAttempts = max;
}
public void setGameErrorHandler(GameErrorHandler mGameErrorHandler) {
this.mGameErrorHandler = mGameErrorHandler;
}
void assertConfigured(String operation) {
if (!mSetupDone) {
String error = "GameHelper error: Operation attempted without setup: "
+ operation
+ ". The setup() method must be called before attempting any other operation.";
logError(error);
throw new IllegalStateException(error);
}
}
private void doApiOptionsPreCheck() {
if (mGoogleApiClientBuilder != null) {
String error = "GameHelper: you cannot call set*ApiOptions after the client "
+ "builder has been created. Call it before calling createApiClientBuilder() "
+ "or setup().";
logError(error);
throw new IllegalStateException(error);
}
}
public void setGamesApiOptions(GamesOptions options) {
doApiOptionsPreCheck();
mGamesApiOptions = options;
}
public void setPlusApiOptions(PlusOptions options) {
doApiOptionsPreCheck();
mPlusApiOptions = options;
}
public GoogleApiClient.Builder createApiClientBuilder() {
if (mSetupDone) {
String error = "GameHelper: you called GameHelper.createApiClientBuilder() after "
+ "calling setup. You can only get a client builder BEFORE performing setup.";
logError(error);
throw new IllegalStateException(error);
}
GoogleApiClient.Builder builder = new GoogleApiClient.Builder(
mActivity, this, this);
if (0 != (mRequestedClients & CLIENT_GAMES)) {
builder.addApi(Games.API, mGamesApiOptions);
builder.addScope(Games.SCOPE_GAMES);
}
if (0 != (mRequestedClients & CLIENT_PLUS)) {
builder.addApi(Plus.API);
builder.addScope(Plus.SCOPE_PLUS_LOGIN);
}
if (0 != (mRequestedClients & CLIENT_SNAPSHOT)) {
builder.addScope(Drive.SCOPE_APPFOLDER);
builder.addApi(Drive.API);
}
mGoogleApiClientBuilder = builder;
return builder;
}
public void setup(GameHelperListener listener) {
if (mSetupDone) {
String error = "GameHelper: you cannot call GameHelper.setup() more than once!";
logError(error);
throw new IllegalStateException(error);
}
mListener = listener;
debugLog("Setup: requested clients: " + mRequestedClients);
if (mGoogleApiClientBuilder == null) {
// we don't have a builder yet, so create one
createApiClientBuilder();
}
mGoogleApiClient = mGoogleApiClientBuilder.build();
mGoogleApiClientBuilder = null;
mSetupDone = true;
}
public GoogleApiClient getApiClient() {
if (mGoogleApiClient == null) {
throw new IllegalStateException(
"No GoogleApiClient. Did you call setup()?");
}
return mGoogleApiClient;
}
public boolean isSignedIn() {
return mGoogleApiClient != null && mGoogleApiClient.isConnected();
}
public boolean isConnecting() {
return mConnecting;
}
public boolean hasSignInError() {
return mSignInFailureReason != null;
}
public SignInFailureReason getSignInError() {
return mSignInFailureReason;
}
public void setShowErrorDialogs(boolean show) {
mShowErrorDialogs = show;
}
public void onStart(Activity act) {
mActivity = act;
mAppContext = act.getApplicationContext();
debugLog("onStart");
assertConfigured("onStart");
if (mConnectOnStart) {
if (mGoogleApiClient.isConnected()) {
Log.w(TAG,
"GameHelper: client was already connected on onStart()");
} else {
debugLog("Connecting client.");
mConnecting = true;
mGoogleApiClient.connect();
}
} else {
debugLog("Not attempting to connect becase mConnectOnStart=false");
debugLog("Instead, reporting a sign-in failure.");
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
notifyListener(false);
}
}, 1000);
}
}
public void onStop() {
debugLog("onStop");
assertConfigured("onStop");
if (mGoogleApiClient.isConnected()) {
debugLog("Disconnecting client due to onStop");
mGoogleApiClient.disconnect();
} else {
debugLog("Client already disconnected when we got onStop.");
}
mConnecting = false;
mExpectingResolution = false;
// let go of the Activity reference
mActivity = null;
}
public String getInvitationId() {
if (!mGoogleApiClient.isConnected()) {
Log.w(TAG,
"Warning: getInvitationId() should only be called when signed in, "
+ "that is, after getting onSignInSuceeded()");
}
return mInvitation == null ? null : mInvitation.getInvitationId();
}
public Invitation getInvitation() {
if (!mGoogleApiClient.isConnected()) {
Log.w(TAG,
"Warning: getInvitation() should only be called when signed in, "
+ "that is, after getting onSignInSuceeded()");
}
return mInvitation;
}
public boolean hasInvitation() {
return mInvitation != null;
}
public boolean hasTurnBasedMatch() {
return mTurnBasedMatch != null;
}
public boolean hasRequests() {
return mRequests != null;
}
public void clearInvitation() {
mInvitation = null;
}
public void clearTurnBasedMatch() {
mTurnBasedMatch = null;
}
public void clearRequests() {
mRequests = null;
}
public TurnBasedMatch getTurnBasedMatch() {
if (!mGoogleApiClient.isConnected()) {
Log.w(TAG,
"Warning: getTurnBasedMatch() should only be called when signed in, "
+ "that is, after getting onSignInSuceeded()");
}
return mTurnBasedMatch;
}
public ArrayList<GameRequest> getRequests() {
if (!mGoogleApiClient.isConnected()) {
Log.w(TAG, "Warning: getRequests() should only be called "
+ "when signed in, "
+ "that is, after getting onSignInSuceeded()");
}
return mRequests;
}
public void enableDebugLog(boolean enabled) {
mDebugLog = enabled;
if (enabled) {
debugLog("Debug log enabled.");
}
}
#Deprecated
public void enableDebugLog(boolean enabled, String tag) {
Log.w(TAG, "GameHelper.enableDebugLog(boolean,String) is deprecated. "
+ "Use GameHelper.enableDebugLog(boolean)");
enableDebugLog(enabled);
}
public void signOut() {
if (!mGoogleApiClient.isConnected()) {
// nothing to do
debugLog("signOut: was already disconnected, ignoring.");
return;
}
// for Plus, "signing out" means clearing the default account and
// then disconnecting
if (0 != (mRequestedClients & CLIENT_PLUS)) {
debugLog("Clearing default account on PlusClient.");
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
}
// For the games client, signing out means calling signOut and
// disconnecting
if (0 != (mRequestedClients & CLIENT_GAMES)) {
debugLog("Signing out from the Google API Client.");
Games.signOut(mGoogleApiClient);
}
// Ready to disconnect
debugLog("Disconnecting client.");
mConnectOnStart = false;
mConnecting = false;
mGoogleApiClient.disconnect();
}
public void onActivityResult(int requestCode, int responseCode,
Intent intent) {
debugLog("onActivityResult: req="
+ (requestCode == RC_RESOLVE ? "RC_RESOLVE" : String
.valueOf(requestCode)) + ", resp="
+ GameHelperUtils.activityResponseCodeToString(responseCode));
if (requestCode != RC_RESOLVE) {
debugLog("onActivityResult: request code not meant for us. Ignoring.");
return;
}
// no longer expecting a resolution
mExpectingResolution = false;
/* if (!mConnecting) {
debugLog("onActivityResult: ignoring because we are not connecting.");
return;
}*/
if (responseCode == Activity.RESULT_OK) {
// Ready to try to connect again.
debugLog("onAR: Resolution was RESULT_OK, so connecting current client again.");
connect();
} else if (responseCode == GamesActivityResultCodes.RESULT_RECONNECT_REQUIRED) {
debugLog("onAR: Resolution was RECONNECT_REQUIRED, so reconnecting.");
connect();
fireOnReconectRequired();
} else if (responseCode == Activity.RESULT_CANCELED) {
// User cancelled.
debugLog("onAR: Got a cancellation result, so disconnecting.");
mSignInCancelled = true;
mConnectOnStart = false;
mUserInitiatedSignIn = false;
mSignInFailureReason = null; // cancelling is not a failure!
mConnecting = false;
mGoogleApiClient.disconnect();
// increment # of cancellations
int prevCancellations = getSignInCancellations();
int newCancellations = incrementSignInCancellations();
debugLog("onAR: # of cancellations " + prevCancellations + " --> "
+ newCancellations + ", max " + mMaxAutoSignInAttempts);
notifyListener(false);
} else {
// Whatever the problem we were trying to solve, it was not
// solved. So give up and show an error message.
debugLog("onAR: responseCode="
+ GameHelperUtils
.activityResponseCodeToString(responseCode)
+ ", so giving up.");
giveUp(new SignInFailureReason(mConnectionResult.getErrorCode(),
responseCode));
}
}
void notifyListener(boolean success) {
debugLog("Notifying LISTENER of sign-in "
+ (success ? "SUCCESS"
: mSignInFailureReason != null ? "FAILURE (error)"
: "FAILURE (no error)"));
if (mListener != null) {
if (success) {
mListener.onSignInSucceeded();
} else {
mListener.onSignInFailed();
}
}
}
public void beginUserInitiatedSignIn() {
debugLog("beginUserInitiatedSignIn: resetting attempt count.");
resetSignInCancellations();
mSignInCancelled = false;
mConnectOnStart = true;
if (mGoogleApiClient.isConnected()) {
// nothing to do
logWarn("beginUserInitiatedSignIn() called when already connected. "
+ "Calling listener directly to notify of success.");
notifyListener(true);
return;
} else if (mConnecting) {
logWarn("beginUserInitiatedSignIn() called when already connecting. "
+ "Be patient! You can only call this method after you get an "
+ "onSignInSucceeded() or onSignInFailed() callback. Suggestion: disable "
+ "the sign-in button on startup and also when it's clicked, and re-enable "
+ "when you get the callback.");
// ignore call (listener will get a callback when the connection
// process finishes)
return;
}
debugLog("Starting USER-INITIATED sign-in flow.");
mUserInitiatedSignIn = true;
if (mConnectionResult != null) {
debugLog("beginUserInitiatedSignIn: continuing pending sign-in flow.");
mConnecting = true;
resolveConnectionResult();
} else {
// We don't have a pending connection result, so start anew.
debugLog("beginUserInitiatedSignIn: starting new sign-in flow.");
mConnecting = true;
connect();
}
}
void connect() {
if (mGoogleApiClient.isConnected()) {
debugLog("Already connected.");
return;
}
debugLog("Starting connection.");
mConnecting = true;
mInvitation = null;
mTurnBasedMatch = null;
mGoogleApiClient.connect();
}
public void reconnectClient() {
if (!mGoogleApiClient.isConnected()) {
Log.w(TAG, "reconnectClient() called when client is not connected.");
// interpret it as a request to connect
connect();
} else {
debugLog("Reconnecting client.");
mGoogleApiClient.reconnect();
}
}
#Override
public void onConnected(Bundle connectionHint) {
debugLog("onConnected: connected!");
if (connectionHint != null) {
debugLog("onConnected: connection hint provided. Checking for invite.");
Invitation inv = connectionHint
.getParcelable(Multiplayer.EXTRA_INVITATION);
if (inv != null && inv.getInvitationId() != null) {
// retrieve and cache the invitation ID
debugLog("onConnected: connection hint has a room invite!");
mInvitation = inv;
debugLog("Invitation ID: " + mInvitation.getInvitationId());
}
// Do we have any requests pending?
mRequests = Games.Requests
.getGameRequestsFromBundle(connectionHint);
if (!mRequests.isEmpty()) {
// We have requests in onConnected's connectionHint.
debugLog("onConnected: connection hint has " + mRequests.size()
+ " request(s)");
}
debugLog("onConnected: connection hint provided. Checking for TBMP game.");
mTurnBasedMatch = connectionHint
.getParcelable(Multiplayer.EXTRA_TURN_BASED_MATCH);
}
// we're good to go
succeedSignIn();
}
void succeedSignIn() {
debugLog("succeedSignIn");
mSignInFailureReason = null;
mConnectOnStart = true;
mUserInitiatedSignIn = false;
mConnecting = false;
notifyListener(true);
}
private final String GAMEHELPER_SHARED_PREFS = "GAMEHELPER_SHARED_PREFS";
private final String KEY_SIGN_IN_CANCELLATIONS = "KEY_SIGN_IN_CANCELLATIONS";
// Return the number of times the user has cancelled the sign-in flow in the
// life of the app
int getSignInCancellations() {
SharedPreferences sp = mAppContext.getSharedPreferences(
GAMEHELPER_SHARED_PREFS, Context.MODE_PRIVATE);
return sp.getInt(KEY_SIGN_IN_CANCELLATIONS, 0);
}
int incrementSignInCancellations() {
int cancellations = getSignInCancellations();
SharedPreferences.Editor editor = mAppContext.getSharedPreferences(
GAMEHELPER_SHARED_PREFS, Context.MODE_PRIVATE).edit();
editor.putInt(KEY_SIGN_IN_CANCELLATIONS, cancellations + 1);
editor.commit();
return cancellations + 1;
}
void resetSignInCancellations() {
SharedPreferences.Editor editor = mAppContext.getSharedPreferences(
GAMEHELPER_SHARED_PREFS, Context.MODE_PRIVATE).edit();
editor.putInt(KEY_SIGN_IN_CANCELLATIONS, 0);
editor.commit();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// save connection result for later reference
debugLog("onConnectionFailed");
mConnectionResult = result;
debugLog("Connection failure:");
debugLog(" - code: "
+ GameHelperUtils.errorCodeToString(mConnectionResult
.getErrorCode()));
debugLog(" - resolvable: " + mConnectionResult.hasResolution());
debugLog(" - details: " + mConnectionResult.toString());
int cancellations = getSignInCancellations();
boolean shouldResolve = false;
if (mUserInitiatedSignIn) {
debugLog("onConnectionFailed: WILL resolve because user initiated sign-in.");
shouldResolve = true;
} else if (mSignInCancelled) {
debugLog("onConnectionFailed WILL NOT resolve (user already cancelled once).");
shouldResolve = false;
} else if (cancellations < mMaxAutoSignInAttempts) {
debugLog("onConnectionFailed: WILL resolve because we have below the max# of "
+ "attempts, "
+ cancellations
+ " < "
+ mMaxAutoSignInAttempts);
shouldResolve = true;
} else {
shouldResolve = false;
debugLog("onConnectionFailed: Will NOT resolve; not user-initiated and max attempts "
+ "reached: "
+ cancellations
+ " >= "
+ mMaxAutoSignInAttempts);
}
if (!shouldResolve) {
// Fail and wait for the user to want to sign in.
debugLog("onConnectionFailed: since we won't resolve, failing now.");
mConnectionResult = result;
mConnecting = false;
notifyListener(false);
return;
}
debugLog("onConnectionFailed: resolving problem...");
resolveConnectionResult();
}
void resolveConnectionResult() {
// Try to resolve the problem
if (mExpectingResolution) {
debugLog("We're already expecting the result of a previous resolution.");
return;
}
if (mActivity == null) {
debugLog("No need to resolve issue, activity does not exist anymore");
return;
}
debugLog("resolveConnectionResult: trying to resolve result: "
+ mConnectionResult);
if (mConnectionResult.hasResolution()) {
// This problem can be fixed. So let's try to fix it.
debugLog("Result has resolution. Starting it.");
try {
// launch appropriate UI flow (which might, for example, be the
// sign-in flow)
mExpectingResolution = true;
mConnectionResult.startResolutionForResult(mActivity,
RC_RESOLVE);
} catch (SendIntentException e) {
// Try connecting again
debugLog("SendIntentException, so connecting again.");
connect();
}
} else {
// It's not a problem what we can solve, so give up and show an
// error.
debugLog("resolveConnectionResult: result has no resolution. Giving up.");
giveUp(new SignInFailureReason(mConnectionResult.getErrorCode()));
mConnectionResult = null;
}
}
public void disconnect() {
if (mGoogleApiClient.isConnected()) {
debugLog("Disconnecting client.");
mGoogleApiClient.disconnect();
} else {
Log.w(TAG,
"disconnect() called when client was already disconnected.");
}
}
void giveUp(SignInFailureReason reason) {
mConnectOnStart = false;
disconnect();
mSignInFailureReason = reason;
if (reason.mActivityResultCode == GamesActivityResultCodes.RESULT_APP_MISCONFIGURED) {
// print debug info for the developer
GameHelperUtils.printMisconfiguredDebugInfo(mAppContext);
}
showFailureDialog();
mConnecting = false;
notifyListener(false);
}
#Override
public void onConnectionSuspended(int cause) {
debugLog("onConnectionSuspended, cause=" + cause);
disconnect();
mSignInFailureReason = null;
debugLog("Making extraordinary call to onSignInFailed callback");
mConnecting = false;
notifyListener(false);
}
. . .
void debugLog(String message) {
if (mDebugLog) {
Log.d(TAG, message);
}
}
void logWarn(String message) {
Log.w(TAG, "!!! GameHelper WARNING: " + message);
}
void logError(String message) {
Log.e(TAG, "*** GameHelper ERROR: " + message);
}
// Represents the reason for a sign-in failure
public static class SignInFailureReason {
public static final int NO_ACTIVITY_RESULT_CODE = -100;
int mServiceErrorCode = 0;
int mActivityResultCode = NO_ACTIVITY_RESULT_CODE;
public int getServiceErrorCode() {
return mServiceErrorCode;
}
public int getActivityResultCode() {
return mActivityResultCode;
}
public SignInFailureReason(int serviceErrorCode, int activityResultCode) {
mServiceErrorCode = serviceErrorCode;
mActivityResultCode = activityResultCode;
}
public SignInFailureReason(int serviceErrorCode) {
this(serviceErrorCode, NO_ACTIVITY_RESULT_CODE);
}
public void setConnectOnStart(boolean connectOnStart) {
debugLog("Forcing mConnectOnStart=" + connectOnStart);
mConnectOnStart = connectOnStart;
}
}
I've tried to change the score, but there is nothing, I have also checked that the leaderboard is set up correctly.
I'm writinng Android app that receiving data via bluetooth from another device. Those data as in fact streaming non-stop. After getting about 50 or 70 of them, app slows down and stop showing me received data. App cache is full, but clearing it (deleting context.getCacheDir()) doesn't help. After restarting whole app, I can again get next part of data. WHat can I do for avoiding this "lag"?
my MainActivity:
public class MainActivity extends Activity {
private BluetoothAdapter bluetoothAdapter;
private boolean pendingRequestEnableBt = false;
private final String SAVED_PENDING_REQUEST_ENABLE_BT = "PENDING_REQUEST_ENABLE_BT";
private BluetoothResponseHandler mHandler;
private static MainActivity instance;
private DeviceConnector connector;
private TextView console;
private String deviceName;
private final int REQUEST_CONNECT_DEVICE = 1;
private final int REQUEST_ENABLE_BT = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
instance = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
console = (TextView) findViewById(R.id.main_text_console);
if (savedInstanceState != null) {
pendingRequestEnableBt = savedInstanceState.getBoolean(SAVED_PENDING_REQUEST_ENABLE_BT);
}
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "No bluetooth available", Toast.LENGTH_LONG).show();
}
if (mHandler == null) {
mHandler = new BluetoothResponseHandler(this);
} else {
mHandler.setTarget(this);
}
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
getActionBar().setSubtitle(deviceName);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(SAVED_PENDING_REQUEST_ENABLE_BT, pendingRequestEnableBt);
outState.putString("device_name", deviceName);
if (console != null) {
final String log = console.getText().toString();
outState.putString("AC", log);
}
}
public boolean isAdapterReady() {
return (bluetoothAdapter != null) && (bluetoothAdapter.isEnabled());
}
private static class BluetoothResponseHandler extends Handler {
private WeakReference<MainActivity> mActivity;
public BluetoothResponseHandler(MainActivity activity) {
mActivity = new WeakReference<MainActivity>(activity);
}
public void setTarget(MainActivity target) {
mActivity.clear();
mActivity = new WeakReference<MainActivity>(target);
}
#Override
public void handleMessage(Message msg) {
MainActivity activity = mActivity.get();
if (activity != null) {
if (msg.what==MessageType.MESSAGE_STATE_CHANGE.getValue()) {
final ActionBar bar = activity.getActionBar();
switch (msg.arg1) {
case DeviceConnector.STATE_CONNECTED:
bar.setSubtitle("Połączono.");
break;
case DeviceConnector.STATE_CONNECTING:
bar.setSubtitle("Łączenie");
break;
case DeviceConnector.STATE_NONE:
bar.setSubtitle("Rozłączono.");
break;
}
} else if (msg.what==MessageType.MESSAGE_READ.getValue()) {
if (msg.obj != null) {
activity.appendLog((String)msg.obj);
}
} else if (msg.what==MessageType.MESSAGE_DEVICE_NAME.getValue()) {
activity.setDeviceName((String) msg.obj);
}
}
}
}
private void startDeviceListActivity() {
stopConnection();
startActivityForResult(new Intent(this, DeviceListActivity.class), REQUEST_CONNECT_DEVICE);
}
private void stopConnection() {
if (connector != null) {
connector.stop();
connector = null;
}
}
#Override
public boolean onSearchRequested() {
if (isAdapterReady()) {
startDeviceListActivity();
}
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.device_control_activity, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
String address = data.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
if (isAdapterReady() && (connector == null)) setupConnector(device);
}
break;
case REQUEST_ENABLE_BT:
pendingRequestEnableBt = false;
if (resultCode != Activity.RESULT_OK) {
Toast.makeText(this, "Bt not enabled", Toast.LENGTH_LONG).show();
}
break;
}
}
private void setupConnector(BluetoothDevice connectedDevice) {
stopConnection();
connector = new DeviceConnector(new DeviceData(connectedDevice, getString(R.string.empty_device_name)), mHandler);
connector.connect();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search:
if (isAdapterReady()) {
if (isConnected()) {
stopConnection();
} else {
startDeviceListActivity();
}
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void appendLog(String message) {
String msg = message.replaceAll("[\n\t\r ]*", "");
console.append(msg.length() + ": " + msg + "\n");
final int scrollAmount = console.getLayout().getLineTop(console.getLineCount()) - console.getHeight();
console.scrollTo(0, scrollAmount>0?scrollAmount:0);
delete(getCacheDir());
}
private boolean isConnected() {
return (connector != null) && (connector.getState() == DeviceConnector.STATE_CONNECTED);
}
public static MainActivity getInstance() {
return instance;
}
public void delete(File file) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
for (File f:file.listFiles()) {
delete(f);
}
}
}
}
}
this code is downloaded, it isn't mine, I just modified it.
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);
}