Play Service wont submit score - android

Im running into a problem when trying to submit a score to my Play Services Leader board. From my MainActivity the user is logged in successfully then from my GameScreen activity I try to submit a score but it fails:(...My Question is does the connection persist or do I have to reconnect the user before I submit???
MAIN ACTIVITY.
public class MainActivity extends BaseGameActivity implements View.OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
Button siButton;
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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();
siButton = (Button) findViewById(R.id.sign_out_button);
siButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (view.getId() == R.id.sign_in_button) {
beginUserInitiatedSignIn();
} else if (view.getId() == R.id.sign_out_button) {
signOut();
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_button).setVisibility(View.GONE);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onSignInSucceeded() {
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_button).setVisibility(View.VISIBLE);
}
#Override
public void onSignInFailed() {
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_button).setVisibility(View.GONE);
}
#Override
public void onClick(View v) {
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
GAMESCREEN
public class GameScreen extends BaseGameActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private int c;
private GoogleApiClient mGoogleApiClient;
TextView counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_screen);
setRequestedClients(BaseGameActivity.CLIENT_GAMES | BaseGameActivity.CLIENT_APPSTATE);
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();
private void progressSetup() {
Thread timerThread = new
Thread() {
#Override
public void run() {
try {
while (mbActive && (waited < TIMER_RUNTIME)) {
sleep(THREAD_SLEEP);
if (mbActive) {
waited += 100;
updateProgress(waited);
if (waited > 9999) {
mbActive = false;
gameOver();
}
}
}
} catch (InterruptedException e) {
Log.d("fail", "failure" + e);
}
}
};
startTread = false;
timerThread.start();
}
private void updateProgress(final int timePassed) {
if (null != mProgressBar) {
progress = mProgressBar.getMax() * timePassed / TIMER_RUNTIME;
mProgressBar.setProgress(progress);
}
}
//game over
private void gameOver() {
runOnUiThread(new Runnable() {
#Override
public void run() {
upDateScore();
}
});
}
private void upDateScore(){
if (mGoogleApiClient.isConnected()) {
Games.Leaderboards.submitScore(mGoogleApiClient, getString(R.string.app_id), c);
Log.d("connectted.....................................................");
} else {
Log.d("not connectted.....................................................");
}
}
#Override
public void onBackPressed() {
Intent home = new Intent(GameScreen.this, MainActivity.class);
home.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(home);
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onSignInFailed() {
}
#Override
public void onSignInSucceeded() {
}
}

Just replace getString(R.string.app_id) with your LEADERBOARD id in method Games.Leaderboards.submitScore(mGoogleApiClient, getString(R.string.app_id).
Leaderboard id looks like this: "CgkI0tXt-q0HEA****"

Ivan Syabro is right. You must use the LEADERBOARD_ID, see Leaderboards in Android - Updating the player's score.
In the developer console's game services section, you can easily export your leaderboard and achievements ids as xml files using the provided button.
In general, using the game services with more than one activity might cause additional waiting periods as each of them signs in individually at its start. Therefore, as far as I know, the implementation with fragments should be preferred, see this famous example playgameservices/android-basic-samples.

Related

When I must reward player for watching video in the core (libgdx)?

I am making a game on LibGdx that has video ads. I implemented interface and it's methods. Everything works, video is shown.
AndroidLauncher:
public class MainAndroidLauncherAuthorization extends AndroidApplication implements
AdsController, RewardedVideoAdListener, AdHandler {
private static final String TAG = "GoogleActivity";
private static final int RC_SIGN_IN = 9001;
private FirebaseAuth mAuth;
private GoogleSignInClient mGoogleSignInClient;
private RewardedVideoAd rewardedVideoAd;
private boolean isRewardLoaded;
private boolean completed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
setContentView(R.layout.activity);
initialize(new STARTGame(this, this), config);
MobileAds.initialize(this, "ca-app-pub-3940256099942544/5224354917");
rewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
rewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
public void loadRewardedVideoAd() {
isRewardLoaded=false;
rewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917", new
AdRequest.Builder().build());
}
#Override
public void onRewardedVideoAdLoaded() {
isRewardLoaded =true;
}
#Override
public void showRewardedVideo() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (rewardedVideoAd.isLoaded()) {
rewardedVideoAd.show();
} else {
loadRewardedVideoAd();
}
}
});
}
#Override
public boolean hasVideoReward(){
return isRewardLoaded;
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem reward) {
loadRewardedVideoAd();
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
completed = true;
}
#Override
public boolean addCoins() {
return completed;
}
#Override
protected void onResume() {
super.onResume();
rewardedVideoAd.resume(this);
}
#Override
public void onPause() {
super.onPause();
rewardedVideoAd.pause(this);
}
#Override
public void onDestroy() {
super.onDestroy();
rewardedVideoAd.destroy(this);
}
#Override
public void coin_10() {
Prefs prefs = new Prefs();
prefs.plus_Coins_bank(10);
}
}
Interface:
public interface AdsController {
void showRewardedVideo();
void loadRewardedVideoAd();
boolean addCoins();
boolean hasVideoReward();
Core:
public class Win_01_18 extends Window implements AdsController, AdHandler {
private Prefs prefs;
public Win_01_18(AdHandler sums, final AdsController adsController, final AssetMan assetMan) {
super("", assetMan.get_skin_dialogs(), "dialog_window_main");
*******
Button btn_buy_10 = new Button(assetMan.get_skin_buttons_coins_video(), "btn_video_long");
***
btn_buy_10.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
adsController.showRewardedVideo();
super.clicked(event, x, y);
}
});
#Override
public void showRewardedVideo() {
}
#Override
public void loadRewardedVideoAd() {
}
#Override
public boolean addCoins() {
return false;
}
#Override
public boolean hasVideoReward() {
return false;
}
#Override
public void coin_10() {
}
Everything works. There are 2 questions:
1 - How to check the onRewardedVideoCompleted() method from core-class?
2 - On what event should the coins be added for watching a video in the core-class?
I am currently trying this myself. But what about changing the
void showRewardedVideoAd()
to a boolean
boolean showRewardedVideoAd()
And then in the onRewardedVideoCompleted() you return true and if it fails you return false.
Then in the core where you call the ad you put
boolean adFinished = False;
adFinished = adsController.showRewardedVideo();
if(adFinished){
// give them the coins or whatever
} else {
// the ad failed or the clicked it away early or something. Don't give them coins and go on
}

Android Wearable Data Layer won't sync.

I am trying to use Data sync between watch and my phone but I am failing miserably on that.
Mobile side :
package com.off.testcomm;
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setOnClickListener((Button) findViewById(R.id.button));
initGoogleAPIClient();
}
private void setOnClickListener(Button button) {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("OFF", "increase counter");
PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/count");
putDataMapReq.getDataMap().putInt("COUNT_COUNT", 7);
PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq)
.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(DataApi.DataItemResult dataItemResult) {
Log.i("OFF", "SaveConfig: " + dataItemResult.getStatus() + ", " + dataItemResult.getDataItem().getUri());
}
});
}
});
}
private void initGoogleAPIClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle connectionHint) {
Log.d("OFF", "onConnected: " + connectionHint);
// Now you can use the Data Layer API
}
#Override
public void onConnectionSuspended(int cause) {
Log.d("OFF", "onConnectionSuspended: " + cause);
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.d("OFF", "onConnectionFailed: " + result);
}
})
// Request access only to the Wearable API
.addApi(Wearable.API)
.build();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
When I click the button I get :
SaveConfig: Status{statusCode=SUCCESS, resolution=null}, wear://ad9cb4db-c697-4777-9088-0b29b8584043/count
So I assume it is sent.
On Wear :
package com.off.testcomm;
public class MyWatchFace extends CanvasWatchFaceService {
...
private class Engine extends CanvasWatchFaceService.Engine implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,DataApi.DataListener, MessageApi.MessageListener {
#Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
#Override
public void onVisibilityChanged(boolean visible) {
if (visible) {
Log.i("OFF","is visible");
registerReceiver();
mGoogleApiClient.connect();
} ...
#Override
public void onConnected(Bundle bundle) {
Log.i("OFF", "OnConnected ");
Wearable.DataApi.addListener(mGoogleApiClient, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.i("OFF","onConnectionSuspended");
}
#Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
Log.i("OFF","OnDataChanged");
}
#Override
public void onMessageReceived(MessageEvent messageEvent) {
Log.i("OFF","onMessageReceived");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i("OFF","onConnectionFailed");
}
...
On wear last log I am getting is : "OnConnected" . When I click button on mobile nothing seems to be synced on wear.
As you can see both classes are in the same packages.
As for manifests both have :
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
any ideas?
thanks
w.
Since you are adding the same data each time the button is clicked, there is no "change" in the exiting data, hence you don't receive an onDataChanged() callback; Android Wear framework looks at the content of your data and decided if it is a new one or not and if it doesn't see any change in the content (assuming that its path doesn't change either), it won't considers that a new one. Add a timestamp to your data and that should make it a new data each time, and should trigger the callback:
putDataMapReq.getDataMap().putLong("timestamp", System.currentTimeMillis());

Call non parent activity's method from fragment

i have one login activity in which i am login using google. after successfully login i am moving to main screen. which has navigation drawer. now from the list of fragments, i want to sign out from google using one of fragment. how can i achieve this. below is my code:
LoginActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Session Manager
session = new SessionManager(getApplicationContext());
initUi();
setupListeners();
}
protected void onStart() {
super.onStart();
}
protected void onStop() {
super.onStop();
if (MyApplication.mGoogleApiClient.isConnected()) {
MyApplication.mGoogleApiClient.disconnect();
}
}
private void initUi(){
llGoogle = (LinearLayout)findViewById(R.id.activity_login_llsignin_google);
}
private void setupListeners(){
llGoogle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (session.isConnected()) {
getProfileInformation();
} else {
}
}
});
}
private void resolveSignInError() {
if (MyApplication.mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
MyApplication.mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
MyApplication.mGoogleApiClient.connect();
}
}
}
private void googlePlusLogin() {
MyApplication.googlePlusLogin();
resolveSignInError();
}
MyApplication.java
public class MyApplication extends Application implements
ConnectionCallbacks, OnConnectionFailedListener,
ResultCallback<People.LoadPeopleResult>{
public static Typeface app_medium;
public static Typeface app_regular;
public static Typeface app_bold;
public static final String TAG = MyApplication.class.getSimpleName();
private static SharedPreferences Pref;
private static MyApplication mInstance;
private static final int RC_SIGN_IN = 0;
// Google client to communicate with Google
public static GoogleApiClient mGoogleApiClient;
public boolean mIntentInProgress;
public static boolean signedInUser;
public static ConnectionResult mConnectionResult;
#SuppressWarnings("unused")
public void onCreate() {
super.onCreate();
mInstance = this;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API, Plus.PlusOptions.builder().build())
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
Pref = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
checkFBKey();
app_regular = Typeface.createFromAsset(getAssets(),
"fonts/dax_regular.ttf");
app_medium = Typeface.createFromAsset(getAssets(),
"fonts/dax_medium.ttf");
app_bold = Typeface.createFromAsset(getAssets(),
"fonts/dax_bold.ttf");
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
/**
* set user login
* */
// public static void setUserFBLogin() {
// // TODO Auto-generated method stub
// Editor edit_login_detail = Pref.edit();
// edit_login_detail.putBoolean(GeneralClass.temp_iUserFaceBookBLOGIN,
// true);
// edit_login_detail.commit();
// }
public void checkFBKey() {
PackageInfo info;
try {
info = getPackageManager().getPackageInfo(getPackageName(),
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String something = new String(Base64.encode(md.digest(), 0));
// String something = new
// String(Base64.encodeBytes(md.digest()));
Log.e("hash key", something);
}
} catch (NameNotFoundException e1) {
Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
Log.e("exception", e.toString());
}
}
public static void googlePlusLogin() {
if (!mGoogleApiClient.isConnecting()) {
signedInUser = true;
}
}
public static void googlePlusLogout() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
// updateProfile(false);
}
}
public static void revokeGplusAccess() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status arg0) {
Log.e("LOGIN", "User access revoked!");
mGoogleApiClient.connect();
}
});
}
}
#Override
public void onLowMemory() {
// TODO Auto-generated method stub
super.onLowMemory();
}
#Override
public void onResult(LoadPeopleResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
if (!arg0.hasResolution()) {
return;
}
if (!mIntentInProgress) {
// store mConnectionResult
MyApplication.mConnectionResult = arg0;
if (signedInUser) {
}
}
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
Log.e("APPLICATION", "CONNECTED");
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
mGoogleApiClient.connect();
}
}
Now, i want to use googlePlusLogout() method in my fragment. how can i do that.?
You should implement all your global credential and methods in Application class so you call it from any Activity or Fragment class.
Declare Set your LoginActivity as CurrentActivity in Application class and using instanceOf call loginSuccessful method of LoginActivity from Application at onConnected() method. and you can call logOut method from Fragment of an Application class.
Check Follow Example.
/**
* #author AA-Sk
*
*/
public class MyApplication extends Application {
private Activity mCurrentActivity;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onConnected(Bundle mBundle) {
Activity mActivity = getmCurrentActivity();
if (mActivity != null) {
if (mActivity instanceof LoginActivity) {
LoginActivity mLoginActivity = (LoginActivity) mActivity;
mLoginActivity.loginSuccessfull(mBundle);
}
}
}
private void googleLogout() {
}
public void setmCurrentActivity(Activity mCurrentActivity) {
this.mCurrentActivity = mCurrentActivity;
}
public Activity getmCurrentActivity() {
return mCurrentActivity;
}
/**
* #author AA-Sk
*
*/
public class LoginActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((MyApplication) getApplication()).setmCurrentActivity(LoginActivity.this);
}
private void loginSuccessfull(Bundle mBundle) {
// Store Data from bundle and call another activity as user is successfully logged in.
}
}
/**
* #author AA-Sk
*
*/
public class SampleActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
/**
* #author AA-Sk
*
*/
public class logout extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
public logout() {
((MyApplication) getActivity().getApplication()).googleLogout();
}
}
}

Why is GoogleApiClient starting a different activity?

I have the following code which is part of a LoginActivity which is not the MAIN or LAUNCHER activity. This activity is started from the Application Class.
The problem is, after I press the Login button, the Dialog from where I choose an account pops up, I choose one, press the OK button, and afterwards my onStop method is called and the MAIN activity is shown. No other method (including OnConnected) seems to be called afterwards.
Is this a limitation of the GoogleApiClient where I can only use it from the Main Activity ? I haven't been able to find anything regarding this and I have tried changing the Activity to a FragmentActivity with no luck...
#EActivity(R.layout.activity_login)
public class LoginActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
#App
MyApp app;
#ViewById(R.id.layout_login)
LinearLayout layoutLogin;
#ViewById(R.id.layout_loading)
RelativeLayout layoutLoading;
#ViewById(R.id.layout_error)
RelativeLayout layoutError;
private static final int RC_SIGN_IN = 0;
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_PROFILE)
.build();
}
#Override
public void onConnected(Bundle bundle) {
layoutLoading.setVisibility(View.VISIBLE);
layoutLogin.setVisibility(View.GONE);
mSignInClicked = false;
}
#Override
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!mIntentInProgress) {
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();
}
}
}
#Click(R.id.button_sign_in)
public void signInButtonClicked() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
}
It seems setting this in the AndroidManifest results in GoogleApiClient closing the activity in which it resides if it is not the main activity.
android:noHistory="true"

Logging out after successful Google+ sign in

This is a long question and might be confusing, please bear with me.
So i successfully created a Google+ sign in for my Android app following the instructions on the developers.google.com website and it successfully signs a user in.Here is the code of my main Activity.
//..imports
#SuppressWarnings("unused")
public class MainActivity extends Activity implements
ConnectionCallbacks, OnConnectionFailedListener, View.OnClickListener {
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
private static final String TAG = "MainActivity";
private ProgressDialog mConnectionProgressDialog;
private static PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlusClient = new PlusClient.Builder(this, this, this)
.setActions("http://schemas.google.com/AddActivity", "http://schemas.google.com/BuyActivity")
.setScopes(Scopes.PLUS_LOGIN) // recommended login scope for social features
// .setScopes("profile") // alternative basic login scope
.build();
// Progress bar to be displayed if the connection failure is not resolved.
mConnectionProgressDialog = new ProgressDialog(this);
mConnectionProgressDialog.setMessage("Signing in...");
}
#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);
findViewById(R.id.sign_in_button).setOnClickListener(this);
return true;
}
protected void onStart() {
super.onStart();
mPlusClient.connect();
}
protected void onStop() {
super.onStop();
mPlusClient.disconnect();
}
public PlusClient getMplusClient() {
return mPlusClient;
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mConnectionProgressDialog.isShowing()) {
// The user clicked the sign-in button already. Start to resolve
// connection errors. Wait until onConnected() to dismiss the
// connection dialog.
if (result.hasResolution()) {
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
}
// Save the intent so that we can start an activity when the user clicks
// the sign-in button.
mConnectionResult = result;
}
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
}
}
public void onConnected(Bundle connectionHint) {
String accountName = mPlusClient.getAccountName();
Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG).show();
startActivity(new Intent(this, TestActivity.class));
}
public void onDisconnected() {
Log.d(TAG, "disconnected");
}
public void startTestActivity() {
startActivity(new Intent(this, TestActivity.class));
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.sign_in_button && !mPlusClient.isConnected()) {
if (mConnectionResult == null) {
mConnectionProgressDialog.show();
} else {
try {
mConnectionResult.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
// Try connecting again.
mConnectionResult = null;
mPlusClient.connect();
} } } }
}//end of class
`
Now i added a new activity to my project called TestActivity where i have the code to sign a user out of the app.And this TestActivity is started in the MainActivity from the block
public void onConnected(Bundle connectionHint) {
String accountName = mPlusClient.getAccountName();
Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG).show();
startActivity(new Intent(this, TestActivity.class));
}
This works fine and the TestActivity is started when a user is connected to the app, and when i run the app again, this is the activity is see(since the user is still signed in).
Now, the problem is the logout button in the TestActivity class does not do anything.Google's Sign Out method is
public void onClick(View view) {
if (view.getId() == R.id.sign_out_button) {
if (mPlusClient.isConnected()) {
mPlusClient.clearDefaultAccount();
mPlusClient.disconnect();
mPlusClient.connect();
}
}
}
Since mPlusClient is in the MainActivity and is declared as private i added the getMPlusCLient() method you see in the MainActivity (I think this is where my problem starts) which returns mPlusClient, a PlusClient object.Now, i ended up with this as my TestActivity
public class TestActivity extends Activity implements View.OnClickListener{
private Button sign_out_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.test, menu);
sign_out_button = (Button)findViewById(R.id.signOutButton);
sign_out_button.setOnClickListener(this);
return true;
}
public void signOut() {
MainActivity signOutObject = new MainActivity();
if (signOutObject.getMplusClient().isConnected()) {
signOutObject.getMplusClient().clearDefaultAccount();
signOutObject.getMplusClient().disconnect();
signOutObject.getMplusClient().connect();
}
}
#Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.signOutButton:
signOut();
break;
}
}
}
The problem like i stated earlier is the logout button in my TestActivity class does not do anything and no error message is shown in logcat.Where did i go wrong?

Categories

Resources