I'm trying to connect via a quick match. I have everything enabled. APIs are enabled, the debug key and production key are added in the Oauth2 list in Google API Console.
Real-Multiplayer is enabled and game-service is published. I'm trying some sample code in my game, plus i'm signing the user.
I'm getting error 2 in onJoinedRoom
I'm trying to sign-in using this:
public void signInSilently() {
mGoogleSignInClient.silentSignIn().addOnCompleteListener(getActivity(),
new OnCompleteListener<GoogleSignInAccount>() {
#Override
public void onComplete(#NonNull Task<GoogleSignInAccount> task) {
if (task.isSuccessful()) {
//onConnected(task.getResult());
Utils.logDebug("OnlineFragment.startSignInIntent()","onComplete, isSuccessful.");
onConnected(task.getResult());
} else {
startSignInIntent();
Utils.logDebug("OnlineFragment.startSignInIntent()","onComplete, NOT isSuccessful.");
task.getException().printStackTrace();
}
}
});
}
It's always onConnected
private void onConnected(GoogleSignInAccount googleSignInAccount){
mRealTimeMultiplayerClient = Games.getRealTimeMultiplayerClient(getActivity(), googleSignInAccount);
startQuickGame();
}
After connecting, I'm starting the new quick match:
private void startQuickGame() {
if(getActivity() != null){
// auto-match criteria to invite one random automatch opponent.
// You can also specify more opponents (up to 3).
// TODO: Make the first param's value 2
Bundle autoMatchCriteria = RoomConfig.createAutoMatchCriteria(1, 1, ROLE_ANY);
// build the room config:
RoomConfig roomConfig =
RoomConfig.builder(mRoomUpdateCallback)
.setOnMessageReceivedListener(mMessageReceivedHandler)
.setRoomStatusUpdateCallback(mRoomStatusCallbackHandler)
.setAutoMatchCriteria(autoMatchCriteria)
.build();
// prevent screen from sleeping during handshake
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// Save the roomConfig so we can use it if we call leave().
mJoinedRoomConfig = roomConfig;
// create room:
mRealTimeMultiplayerClient.create(mJoinedRoomConfig);
}
}
Then I'm getting the error in the listener (Only the mentioned function from the listener has been included, other functions are not getting called)
private RoomUpdateCallback mRoomUpdateCallback = new RoomUpdateCallback() {
#Override
public void onRoomCreated(int code, #Nullable Room room) {
// Update UI and internal state based on room updates.
if(room != null)
Log.d("SignInGoogleOnlineFrag", "Room isn't null");
if(code == GamesCallbackStatusCodes.OK)
Log.d("SignInGoogleOnlineFrag", "OK");
if (code == GamesCallbackStatusCodes.OK && room != null) {
Log.d("SignInGoogleOnlineFrag", "Room " + room.getRoomId() + " created.");
} else {
Log.w("SignInGoogleOnlineFrag", "Error creating room: " + code);
// let screen go to sleep
getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
Related
When I am trying to pay with the google pay option in my developed android application, I am getting the error
Request failed An unexpected error has occurred Please try again later [R_BIBED_07]
For the merchant, we are using stripe as a payment gateway. Everything is set ok like the stripe key and environment. This is happening only for production. In test mode, it navigates me to the card selection. But only in production after clicking on the button it shows me the error. I don't know exactly what the reason is. I tried many ways.
I am providing the link for the snippet code I used to integrate Google Pay into my android application.
https://www.tabnine.com/web/assistant/code/rs/5c7c2ad92ef5570001da2491#L164
Code
// Inside OnCreate methos
if (paymentmethod.equals("GooglePay")) {
proceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PaymentDataRequest request = createPaymentDataRequest();
Log.e("onclickreq", String.valueOf(request));
if (request != null) {
AutoResolveHelper.resolveTask(
mPaymentsClient.loadPaymentData(request),
DbsSummaryPage.this,
LOAD_PAYMENT_DATA_REQUEST_CODE);
// LOAD_PAYMENT_DATA_REQUEST_CODE is a constant integer of your choice,
// similar to what you would use in startActivityForResult
} else {
Log.e("Enter in", String.valueOf(request));
Toast.makeText(DbsSummaryPage.this, "gap", Toast.LENGTH_SHORT).show();
}
}
});
}
mPaymentsClient =
Wallet.getPaymentsClient(
this,
new Wallet.WalletOptions.Builder()
.setEnvironment(WalletConstants.ENVIRONMENT_PRODUCTION)
.build());
isReadyToPay();
// End of OnCreate method
private void isReadyToPay() {
Log.e("isReadyToPay","isReadyToPay");
IsReadyToPayRequest request =
IsReadyToPayRequest.newBuilder()
.addAllowedPaymentMethod(WalletConstants.PAYMENT_METHOD_CARD)
.addAllowedPaymentMethod(WalletConstants.PAYMENT_METHOD_TOKENIZED_CARD)
.build();
Task<Boolean> task = mPaymentsClient.isReadyToPay(request);
task.addOnCompleteListener(
new OnCompleteListener<Boolean>() {
public void onComplete(#NonNull Task<Boolean> task) {
try {
boolean result = task.getResult(ApiException.class);
if (result) {
// Show Google as payment option.
System.out.println(true);
System.out.println("resttrtdt" + result);
} else {
// Hide Google as payment option.
System.out.println("hide the google button");
}
} catch (ApiException exception) {
System.out.println("hide the google button");
}
}
});
}
private PaymentDataRequest createPaymentDataRequest() {
Log.e("paydat", String.valueOf(totalamount));
ad = String.format("%.2f", totalamount);
Log.e("adgoggole", ad);
Log.e("Insidetotal", String.valueOf(totalamount));
Log.e("PSPRICE Google", "Hi " + psprice);
PaymentDataRequest.Builder request =
PaymentDataRequest.newBuilder()
.setTransactionInfo(
TransactionInfo.newBuilder()
.setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
.setTotalPrice(ad)
.setCurrencyCode("USD")
.build())
.addAllowedPaymentMethod(WalletConstants.PAYMENT_METHOD_CARD)
.addAllowedPaymentMethod(WalletConstants.PAYMENT_METHOD_TOKENIZED_CARD)
.setCardRequirements(
CardRequirements.newBuilder()
.addAllowedCardNetworks(
Arrays.asList(
WalletConstants.CARD_NETWORK_AMEX,
WalletConstants.CARD_NETWORK_DISCOVER,
WalletConstants.CARD_NETWORK_VISA,
WalletConstants.CARD_NETWORK_MASTERCARD))
.build());
PaymentMethodTokenizationParameters params =
PaymentMethodTokenizationParameters.newBuilder()
.setPaymentMethodTokenizationType(
WalletConstants.PAYMENT_METHOD_TOKENIZATION_TYPE_PAYMENT_GATEWAY)
.addParameter("gateway", "stripe")
.addParameter("stripe:publishableKey", key)
.addParameter("stripe:version", "2018-11-08")
.build();
request.setPaymentMethodTokenizationParameters(params);
System.out.println("Data" + request.build());
return request.build();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("Entered" + "into onactivity");
switch (requestCode) {
case LOAD_PAYMENT_DATA_REQUEST_CODE:
switch (resultCode) {
case Activity.RESULT_OK:
PaymentData paymentData = PaymentData.getFromIntent(data);
String rawToken = paymentData.getPaymentMethodToken().getToken();
Token stripeToken = Token.fromString(rawToken);
String stripegettoken = stripeToken.getId();
System.out.println(paymentData.getPaymentMethodToken().getToken());
System.out.println(rawToken);
System.out.println(paymentData.getPaymentMethodToken().getToken());
System.out.println("rawToken" + rawToken);
if (stripeToken != null) {
// This chargeToken function is a call to your own server, which should then connect
// to Stripe's API to finish the charge.
pd.show();
executeFormForGooglePay(stripegettoken, totalamount, userphonenumber, proprice, producttax, pscommission, finalpsprice, stripefee, salestax, bodatysurcharge, fffee);
}
break;
case Activity.RESULT_CANCELED:
pd.dismiss();
System.out.println("status" + "Cancelled");
break;
case AutoResolveHelper.RESULT_ERROR:
Status status = AutoResolveHelper.getStatusFromIntent(data);
System.out.println("status" + status);
pd.dismiss();
Toast.makeText(DbsSummaryPage.this,
"Got error " + status.getStatusMessage(), Toast.LENGTH_SHORT).show();
// Log the status for debugging.
// Generally, there is no need to show an error to
// the user as the Google Payment API will do that.
break;
default:
// Do nothing.
}
break;
default:
// Do nothing.
}
}
before you use the PRODUCTION environment, your integration needs to be approved from Google Pay & Wallet Console.
In the meantime, you can test your integration using the TEST environment in your configuration.
In my case, i just forgot to add the relevant meta-data in the manifest file under application tag:
<meta-data
android:name="com.google.android.gms.wallet.api.enabled"
android:value="true" />
I'm using this tuto to integrate Play Billing Library to my app: http://www.androidrey.com/implement-play-billing-library-in-android-application/ and all works good ... well, not at all. I have problems to know when a suscription was cancelled, I tested all the methods to find a resultCode or something to know this state, but have a method that I could not implement. Could be this the problem?
class: BillingManager.java
public void queryPurchases() {
Runnable queryToExecute = new Runnable() {
#Override
public void run() {
long time = System.currentTimeMillis();
Purchase.PurchasesResult purchasesResult = billingClient.queryPurchases(BillingClient.SkuType.INAPP);
if (areSubscriptionsSupported()) {
Purchase.PurchasesResult subscriptionResult
= billingClient.queryPurchases(BillingClient.SkuType.SUBS);
System.out.println("QUERY 0");
if (subscriptionResult.getResponseCode() == BillingClient.BillingResponse.OK) {
purchasesResult.getPurchasesList().addAll(
subscriptionResult.getPurchasesList());
System.out.println("QUERY 1");
} else {
// Handle any error response codes.
}
} else if (purchasesResult.getResponseCode() == BillingClient.BillingResponse.OK) {
// Skip subscription purchases query as they are not supported.
System.out.println("QUERY 2");
} else {
// Handle any other error response codes.
System.out.println("QUERY 3");
}
onQueryPurchasesFinished(purchasesResult);
System.out.println("QUERY RESULT "+ purchasesResult);
}
};
executeServiceRequest(queryToExecute);
}
private void onQueryPurchasesFinished(Purchase.PurchasesResult result) {
// Have we been disposed of in the meantime? If so, or bad result code, then quit
if (billingClient == null || result.getResponseCode() != BillingClient.BillingResponse.OK) {
Log.w(TAG, "Billing client was null or result code (" + result.getResponseCode()
+ ") was bad – quitting");
return;
}
Log.d(TAG, "Query inventory was successful.");
// Update the UI and purchases inventory with new list of purchases
// mPurchases.clear();
onPurchasesUpdated(BillingClient.BillingResponse.OK, result.getPurchasesList());
}
public boolean areSubscriptionsSupported() {
int responseCode = billingClient.isFeatureSupported(BillingClient.FeatureType.SUBSCRIPTIONS);
if (responseCode != BillingClient.BillingResponse.OK) {
Log.w(TAG, "areSubscriptionsSupported() got an error response: " + responseCode);
}
return responseCode == BillingClient.BillingResponse.OK;
}
It is supposed to be called here: MyBillingUpdateListener.java
public class MyBillingUpdateListener implements BillingManager.BillingUpdatesListener {
//final BillingManager billingManager = new BillingManager(,this );
#Override
public void onBillingClientSetupFinished() {
//billingManager.queryPurchases(); THIS IS WHAT I COULD NOT IMPLEMENT
}
Any help is welcome, thanks!.
Play Billing 1.0 does not have the concept of purchase states (anymore), so there currently is no way to get this information using the Play Billing library.
My understanding is that queryPurchases is supposed to return actual valid purchases only. However, it gets the information from a long living cache and you have no way of updating it manually.
onBillingClientSetupFinished is completely unrelated.
Here is an active discussion on the subject: https://github.com/googlesamples/android-play-billing/issues/122
I am trying to use 'Authenticate using Cognito-Identity with Cognito user pool' in my Android application. My Cognito user pool authentication works well, when I run that separately and I had seen a JWTToken as well. When I run the the 'PubSub' sample application with Unauthenticated role, it worked as expected. When I integrate these two features in one application, the application threw following error.
W/System.err: MqttException (0) - java.io.IOException: Already connected
W/System.err: at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:38)
W/System.err: at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:664)
W/System.err: at java.lang.Thread.run(Thread.java:761)
W/System.err: Caused by: java.io.IOException: Already connected
W/System.err: at java.io.PipedOutputStream.connect(PipedOutputStream.java:100)
W/System.err: at java.io.PipedInputStream.connect(PipedInputStream.java:195)
W/System.err: at org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketReceiver.<init>(WebSocketReceiver.java:42)
W/System.err: at org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketSecureNetworkModule.start(WebSocketSecureNetworkModule.java:78)
W/System.err: at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650)
W/System.err: ... 1 more
I have been trying to resolve this issue since last Thursday and still stuck at the same place. Really No idea where should i check.!
I am adding my Authentication(Cognito user pool authentication) activity and Connect activity.
AmazonCognitoIdentityProviderClient identityProviderClient = new
AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), new ClientConfiguration());
identityProviderClient.setRegion(Region.getRegion(Regions.US_WEST_2));
CognitoUserPool userPool = new CognitoUserPool(getApplicationContext(), "us-west-2_ghtcc6ho9", "4t0mk45hNso69dp2j4jvel5ghm", "1jmq0lhhq721oif9k6nug31c29i760vihua8hvrgu5umfr2a1vd7", identityProviderClient);
cogUser = userPool.getUser();
authenticationHandler = new AuthenticationHandler() {
#Override
public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice) {
String ids = userSession.getIdToken().getJWTToken();
Log.d("MyToken","session id___"+userSession.getIdToken().getExpiration()+"___"+userSession.getIdToken().getIssuedAt());
Intent pubSub = new Intent(MainActivity.this, PubSubActivity.class);
pubSub.putExtra("token",""+ids);
startActivity(pubSub);
//MainActivity.this.finish();
}
#Override
public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
Log.d("MyToken","getAuthenticationDetails");
AuthenticationDetails authenticationDetails = new AuthenticationDetails("shone", "172737", null);
authenticationContinuation.setAuthenticationDetails(authenticationDetails);
// Allow the sign-in to continue
authenticationContinuation.continueTask();
}
#Override
public void getMFACode(MultiFactorAuthenticationContinuation multiFactorAuthenticationContinuation) {
Log.d("MyToken","getMFACode");
multiFactorAuthenticationContinuation.continueTask();
}
#Override
public void authenticationChallenge(ChallengeContinuation continuation) {
Log.d("MyToken","authenticationChallenge"+continuation.getChallengeName());
newPasswordContinuation.continueTask();
}
#Override
public void onFailure(Exception exception) {
exception.printStackTrace();
Log.d("MyToken","onFailure");
}
};
cogUser.getSessionInBackground(authenticationHandler);
When It reaches 'OnSuccess' I am launching my connect activity and passing my session token along with the Intent. Moving to the next activity
private static final String COGNITO_POOL_ID = "us-west-2:a153a090-508c-44c0-a9dd-efd450298c4b";
private static final Regions MY_REGION = Regions.US_WEST_2;
AWSIotMqttManager mqttManager;
String clientId;
AWSCredentials awsCredentials;
CognitoCachingCredentialsProvider credentialsProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
if(null == intent){
Toast.makeText(getApplicationContext(), "Token is null", Toast.LENGTH_SHORT).show();
}else {
token = intent.getStringExtra("token");
}
clientId = UUID.randomUUID().toString();
credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(),
COGNITO_POOL_ID,
MY_REGION
);
mqttManager = new AWSIotMqttManager(clientId, CUSTOMER_SPECIFIC_ENDPOINT);
Map loginsMap = new HashMap();
loginsMap.put("cognito-idp.us-west-2.amazonaws.com/us-west-2_ghtcc6ho9", token);
credentialsProvider.setLogins(loginsMap);
Log.d("SESSION_ID", ""+token);
new Thread(new Runnable() {
#Override
public void run() {
credentialsProvider.refresh();
awsCredentials = credentialsProvider.getCredentials();
Log.d("SESSION_ID B: ", ""+awsCredentials.getAWSAccessKeyId());
Log.d("SESSION_ID C: ", ""+awsCredentials.getAWSSecretKey());
}
}).start();
}
View.OnClickListener connectClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(LOG_TAG, "clientId = " + clientId);
try {
mqttManager.connect(credentialsProvider, new AWSIotMqttClientStatusCallback() {
#Override
public void onStatusChanged(final AWSIotMqttClientStatus status,
final Throwable throwable) {
Log.d(LOG_TAG, "Status = " + String.valueOf(status)+"______"+((null !=throwable)?throwable.getMessage():""));
runOnUiThread(new Runnable() {
#Override
public void run() {
if (status == AWSIotMqttClientStatus.Connecting) {
tvStatus.setText("Connecting...");
} else if (status == AWSIotMqttClientStatus.Connected) {
tvStatus.setText("Connected");
} else if (status == AWSIotMqttClientStatus.Reconnecting) {
if (throwable != null) {
Log.e(LOG_TAG, "Connection error.", throwable);
}
tvStatus.setText("Reconnecting");
} else if (status == AWSIotMqttClientStatus.ConnectionLost) {
if (throwable != null) {
Log.e(LOG_TAG, "Connection error.", throwable);
throwable.printStackTrace();
}
tvStatus.setText("Disconnected");
} else {
tvStatus.setText("Disconnected");
}
}
});
}
});
} catch (final Exception e) {
Log.e(LOG_TAG, "Connection error.", e);
}
}
};
What is wrong in my code? Why it throws exception when the MQTT connect is being invoked? Any help would be appreciated.
I beat my head up with this almost a week.
Full course of action ->
After succesfull login you will have a jwt token
String idToken = cognitoUserSession.getIdToken().getJWTToken();
put it into a map
Map<String, String> logins = new HashMap<String, String>();
//fill it with Cognito User token
logins.put("cognito-idp.<REGION>.amazonaws.com/<COGNITO_USER_POOL_ID>", idToken);
then use it to set in two places (not stated in any documentation!)
CognitoCachingCredentialsProvider credentialsProvider = new
CognitoCachingCredentialsProvider(context, IDENTITY_POOL_ID, REGION);
credentialsProvider.setLogins(logins);
and
AmazonCognitoIdentity cognitoIdentity = new AmazonCognitoIdentityClient(credentialsProvider);
GetIdRequest getIdReq = new GetIdRequest();
getIdReq.setLogins(logins); //or if you have already set provider logins just use credentialsProvider.getLogins()
getIdReq.setIdentityPoolId(COGNITO_POOL_ID);
GetIdResult getIdRes = cognitoIdentity.getId(getIdReq);
after that you still nedd to make some call
AttachPrincipalPolicyRequest attachPolicyReq = new AttachPrincipalPolicyRequest(); //in docs it called AttachPolicyRequest but it`s wrong
attachPolicyReq.setPolicyName("allAllowed"); //name of your IOTAWS policy
attachPolicyReq.setPrincipal(getIdRes.getIdentityId());
new AWSIotClient(credentialsProvider).attachPrincipalPolicy(attachPolicyReq);
and only after that you can enable connect button and continue like that
mqttManager.connect(credentialsProvider, new AWSIotMqttClientStatusCallback() {
Really for this small piece of code i spent a lot of time...
I was also getting same error -
Feb 27, 2019 10:23:09 AM com.amazonaws.services.iot.client.mqtt.AwsIotMqttConnectionListener onFailure
WARNING: Connect request failure
MqttException (0) - java.io.IOException: Already connected
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:38)
at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:664)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.IOException: Already connected
at java.io.PipedOutputStream.connect(PipedOutputStream.java:100)
but the problem was different.
First of all, you do not need to call attachPrincipalPolicy from code. You can use the command line as well. You can do something like -
aws iot attach-principal-policy --principal us-east-1:1c973d17-98e6-4df6-86bf-d5cedc1fbc0d --policy-name "thingpolicy" --region us-east-1 --profile osfg
You will get the principal ID from identity browser of your identity pool. Now lets come to the error -
To successfully connect to mqtt with authenticated Cognito credentials, you need 2 correct policies -
Authenticated role corresponding to your identity pool should allow all mqtt operations.
AWS IoT policy should allow the same operations and you need to associate your cognito identity with this policy. We use attachPrincipalPolicy to do so.
If anyone step is missed we get above error. I agree the error is misleading - Already connected makes no sense to me for this. I would normally think it has to do with clientId, which should be unique. But anyways hopefully AWS folks would make this better at some point.
For my particular case issue was point 1. Though my IoT policy had all the required permissions, the auth role corresponding to the identity pool did not. So make sure you do that.
I have created a youtube video to show this as well: https://www.youtube.com/watch?v=j2KJVHGHaFc
When a client connected to broker it has a unique client ID. If clients tried to connect with same client id then this error occur. Use different client IDs like foo1, foo2, foo3, etc.
I have implemented functions to save and load snapshots using the Game API from Google Play Services. The next step I am working on is to handle conflicts when there is more then one snapshot. And here comes the problem.
In my understanding a conflict should occure when doing the following:
Save a snapshot after making game progress
Sign out (Google Play Services)
Delete all app data
Start game again and make some progress
Sign in (Google Play Services)
Save a new snapshop
Load snapshop
Unfortunately in my case no conflict occures. Instead the current game progress is being saved (step 6) and loading (step 7) just returns this snapshop. There is no indicator that snapshot (step 1) was overwritten - resulting in loosing game progress.
Code for saving:
private void executeSave() {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
GoogleApiClient googleApiClient = App.getGoogleApiHelper().getmGoogleApiClient();
Snapshots.OpenSnapshotResult openResult = Games.Snapshots.open(googleApiClient, getSavegameFilename(), true).await();
Status resultStatus = openResult.getStatus();
Log.d(TAG, "openstatus is: " + resultStatus.getStatusMessage());
if(resultStatus.isSuccess()) {
byte[] localSavegame = getPersistingManager().readBytes();
if(localSavegame != null) {
Log.d(TAG, "Going to save:" + getPersistingManager().read());
createSnapshot(openResult.getSnapshot(), localSavegame).await();
}
}
}
});
}
private PendingResult<Snapshots.CommitSnapshotResult> createSnapshot(Snapshot snapshot, byte[] data) {
GoogleApiClient googleApiClient = App.getGoogleApiHelper().getmGoogleApiClient();
snapshot.getSnapshotContents().writeBytes(data);
SnapshotMetadataChange metadataChange = new SnapshotMetadataChange.Builder().build();
return Games.Snapshots.commitAndClose(googleApiClient, snapshot, metadataChange);
}
Code for loading:
private void executeLoad() {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
GoogleApiClient googleApiClient = App.getGoogleApiHelper().getmGoogleApiClient();
Snapshots.OpenSnapshotResult result = Games.Snapshots.open(googleApiClient, getSavegameFilename(), true).await();
processResult(result, 0);
}
});
}
private void processResult(Snapshots.OpenSnapshotResult result, int retryCount) {
Status resultStatus = result.getStatus();
retryCount++;
if(resultStatus.isSuccess()) {
Log.d(TAG, "No conflict, thats great!");
handleSuccess(result);
} else if (resultStatus.getStatusCode() == GamesStatusCodes.STATUS_SNAPSHOT_CONFLICT) {
Log.d(TAG, "Aww... a conflict!");
handleConflict(result, retryCount);
} else {
Log.e(TAG, "Error while getting savegame, status message: " + resultStatus.getStatusMessage());
}
}
When performing the steps from above this is happening:
1) Save a snapshot after making game progress
absRemotePersistMgmt: openstatus is: STATUS_OK
absRemotePersistMgmt: Going to save:{"solvedQuestions":{"1":[],"2":[1]}}
6) Save a new snapshot
absRemotePersistMgmt: openstatus is: STATUS_OK
absRemotePersistMgmt: Going to save:{"solvedQuestions":{"1":[1,2],"2":[]}}
7) Load snapshop
absRemotePersistMgmt: No conflict, thats great!
What am I missing?
Sources I used:
https://developers.google.com/games/services/android/savedgames
https://www.youtube.com/watch?v=iHc2RBZs5T0
https://www.youtube.com/watch?v=naQhSkzNGAI
I'm using Facebook Unity Plugin 4.3.4 and having issue with FB.Login()
Using logcat i have solved mismatched app id and key hashes now when i try to login it prompts a blank screen like it is going to authenticate but will then go right back to my application.
The delegate for the FB.Login() is not called until I press the button i assigned as the login button and it will produce the same result.
I do have the facebook app on the device and have tried removing it. When it is removed and i log in through the browser facebook says that the app is already authenticated so I'm assuming a portion of it must of worked for that to have happened
When i debug the result of the login I get no errors and {"is_logged_in":false,"user_id":"","access_token":""}
Right now im outta ideas.
This is the monobehaviour i have attached on the main scene of my application and the login button which is also on the main scene calls FacebookLogin()
using UnityEngine;
using System.Collections;
using JsonFx.Json;
using System.Collections.Generic;
public class FBObject : MonoBehaviour
{
public LGUI3DLabel connectFacebookLbl;
// Use this for initialization
void Awake ()
{
FB.Init(OnFacebookInitComplete, OnUnityHidden);
}
void OnFacebookInitComplete()
{
connectFacebookLbl.text = "AppID = " + FB.AppId;
if(FB.IsLoggedIn)
{
OnLoggedIn();
}
}
void OnUnityHidden(bool isGameShown)
{
if(!isGameShown)
{
Time.timeScale = 0;
}
else
{
Time.timeScale = 1;
}
}
void OnLoggedIn()
{
Debug.Log("Current User ID = " + FB.UserId);
connectFacebookLbl.text = "Id = " + FB.UserId;
}
public void FacebookLogin()
{
if(!FB.IsLoggedIn)
{
FB.Login("email,publish_actions", LoginCallback);
}
else
{
connectFacebookLbl.text = "Is Logged In";
FB.API("/me?fields=id,first_name,friends.limit(100).fields(first_name,id)", Facebook.HttpMethod.GET, GetUserInformation);
}
}
void GetUserInformation(FBResult queryResult)
{
if(queryResult.Error != null)
{
Debug.LogError(queryResult.Error);
connectFacebookLbl.text = "There was an error\n"+queryResult.Error;
return;
}
var reader = new JsonReader();
var output = reader.Read<Dictionary<string, object>>(queryResult.Text);
string userName = (string)output["first_name"];
connectFacebookLbl.text = userName;
}
void LoginCallback(FBResult loginResult)
{
connectFacebookLbl.text = "Trying to log in!";
connectFacebookLbl.text = "Result = " + loginResult.Text;
if(FB.IsLoggedIn)
{
connectFacebookLbl.text = "Wow we actually logged in!!!";
OnLoggedIn();
}
}
// Update is called once per frame
void Update ()
{
}
}