kandi background
Explore Kits

android-basic-samples | Google Play game services - Android samples | Android library

 by   playgameservices Java Version: Current License: Apache-2.0

 by   playgameservices Java Version: Current License: Apache-2.0

Download this library from

kandi X-RAY | android-basic-samples Summary

android-basic-samples is a Java library typically used in Mobile, Android applications.,roid-basic-samples has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has medium support. You can download it from GitHub.
These are the Android samples for Google Play game services. <h2>How to run a sample</h2>. <h3>Building using Android Studio…​</h3>. <h3>Modify IDs, compile and run</h3>.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • android-basic-samples has a medium active ecosystem.
  • It has 939 star(s) with 997 fork(s). There are 135 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 73 open issues and 163 have been closed. On average issues are closed in 269 days. There are 6 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of android-basic-samples is current.
This Library - Support
Best in #Android
Average in #Android
This Library - Support
Best in #Android
Average in #Android

quality kandi Quality

  • android-basic-samples has 0 bugs and 0 code smells.
This Library - Quality
Best in #Android
Average in #Android
This Library - Quality
Best in #Android
Average in #Android

securitySecurity

  • android-basic-samples has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • android-basic-samples code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
This Library - Security
Best in #Android
Average in #Android
This Library - Security
Best in #Android
Average in #Android

license License

  • android-basic-samples is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
This Library - License
Best in #Android
Average in #Android
This Library - License
Best in #Android
Average in #Android

buildReuse

  • android-basic-samples releases are not available. You will need to build from source code and install.
  • Build file is available. You can build the component from source.
  • Installation instructions are not available. Examples and code snippets are available.
  • android-basic-samples saves you 1293 person hours of effort in developing the same functionality from scratch.
  • It has 2903 lines of code, 150 functions and 30 files.
  • It has high code complexity. Code complexity directly impacts maintainability of the code.
This Library - Reuse
Best in #Android
Average in #Android
This Library - Reuse
Best in #Android
Average in #Android
Top functions reviewed by kandi - BETA

kandi has reviewed android-basic-samples and discovered the below as its top functions. This is intended to give you an instant insight into android-basic-samples implemented functionality, and help decide if they suit your requirements.

  • Invoked when an activity is saved .
    • Called when the sign - in button is clicked .
      • Create the view .
        • Creates and returns an adapter which allows to adapt a player to a player .
          • Deletes the specified snapshot .
            • Initializes the game file .
              • Waits for close to open .
                • Close the snapshot .
                  • Creates a union of game game with the given level .
                    • Sets the explanation .

                      Get all kandi verified functions for this library.

                      Get all kandi verified functions for this library.

                      android-basic-samples Key Features

                      CollectAllTheStars2. Demonstrates how to use the Snapshots feature to save game data. The sample signs the user in, synchronizes their data from a named Snapshot, then updates the UI to reflect the game state saved in the Snapshot.

                      TypeANumber. Demonstrates how to use leaderboards, achievements, events, and friends. In this exciting game, you type the score you think you deserve. But wait! There is a twist. If you are playing in easy mode, you get the score you requested. However, if you are playing in hard mode, you only get half! (tough game, we know). You can also check how your friends perform in this game by checking out social leaderboards.

                      Set up the project in the Developer Console by following [these instructions](https://developers.google.com/games/services/console/enabling). Note your package name and the application ID of the project!

                      For the Type a Number sample, you need to create leaderboards/achievements. (You can see the ones that the sample needs in its [res/values/ids.xml](TypeANumber/src/main/res/values/ids.xml) file.) You can create them two ways:

                      Add them via the [Developer console](https://play.google.com/apps/publish/#GameListPlace).

                      Use [this utility](http://playgameservices.github.io/android-basic-samples/config-magic/index.html?sample=typeanumber), which will automatically create them for you.

                      Open Android Studio and launch the Android SDK manager from it (Tools | Android | SDK Manager)

                      Ensure the following components are installed and updated to the latest version.

                      Android SDK Platform-Tools

                      Android Support Repository

                      Google Repository

                      Return to Android Studio and select Open an existing Android Studio project

                      Select the android-basic-samples directory.

                      Change the applicationId in the build.gradle file to your own package name (ie - com.example.package.name) (the same one you registered in Developer Console!). You will have to update the build.gradle file for each sample you want to run. There is no need to edit the AndroidManifest.xml file.

                      In the Developer console, select a resource type (Achievements, Events, Leaderboards) and click "Get Resources". Copy the contents from the console and replace the contents of res/values/ids.xml.

                      If you are running Android Studio, check the TODO window to see if there are any remaining tasks.

                      Compile and run.

                      To [ligi](http://github.com/ligi) for contributing the initial Gradle build files

                      To [bechhansen](https://github.com/bechhansen) for fixing a bug in GameHelper where the turn-based match was being lost when a non-Games client connected.

                      default

                      copy iconCopydownload iconDownload
                      cd /path/to/android-basic-samples
                      export ANDROID_HOME = /path/to/android/sdk
                      ./gradlew build

                      Google play games services : Saved games, creating a new snapshot

                      copy iconCopydownload iconDownload
                      //the data you want to save must be in bytes
                      byte[] bytearray;
                      //name of the snapshot
                      private String currentSave="snapshot"+1235;
                      
                      private void executeSaving(){
                      
                          // get the snapshoClient
                          SnapshotsClient snapshotsClient= Games.getSnapshotsClient(this,account);
                      
                          // to save a game
                          snapshotsClient.open(currentSave,true).addOnCompleteListener(task -> {
                      
                              Snapshot snapshot =task.getResult().getData();
                      
                              if (snapshot != null){
                                  //call of the method writeSnapshot params : the snapshot and the data we 
                                  //want to save with a description
                                  writeSnapshot(snapshot,bytearray,"first description").addOnCompleteListener(task1 -> {
                      
                                      if(task1.isSuccessful()){
                                          Toast.makeText(getApplicationContext(),"Succesful",Toast.LENGTH_SHORT).show();
                                      }else {
                                          Log.e("ERR",""+task1.getException());
                                      }
                                  });
                              }
                          });
                      }
                      
                      private Task<SnapshotMetadata> writeSnapshot(Snapshot snapshot ,byte[] bytearray,String desc){
                      
                          //write your data in the snapshot
                          snapshot.getSnapshotContents().writeBytes(bytearray);
                      
                          SnapshotMetadataChange snapshotMetadata = new SnapshotMetadataChange.Builder().setDescription(desc).build();
                      
                          SnapshotsClient snapshotsClient=Games.getSnapshotsClient(this,account);
                      
                          //commit and close to send the new changes to google play games services
                          return snapshotsClient.commitAndClose(snapshot,snapshotMetadata);
                      }
                      

                      integrating libGDX Game with google play games Leaderboards wit help of android basic examples

                      copy iconCopydownload iconDownload
                      public interface PlayServices
                      {
                      public void signIn();
                      public void signOut();
                      public void rateGame();
                      public void unlockAchievement(String str);
                      public void submitScore(int highScore);
                      public void submitLevel(int highLevel);
                      public void showAchievement();
                      public void showScore();
                      public void showLevel();
                      public boolean isSignedIn();
                      public void showBannerAd();
                      public void hideBannerAd();
                      public void showInterstitialAd (Runnable then);
                      public void showRewardedVideo();
                      public boolean isRewardEarned();
                      }
                      

                      What does "for (int clickableId : clickableIds)" do?

                      copy iconCopydownload iconDownload
                        final int[] clickableIds = new int[]{
                                  R.id.easy_mode_button,
                                  R.id.hard_mode_button,
                                  R.id.show_achievements_button,
                                  R.id.show_leaderboards_button,
                                  R.id.sign_in_button,
                                  R.id.sign_out_button
                          };
                      
                          for (int clickableId : clickableIds) {
                              view.findViewById(clickableId).setOnClickListener(this);
                          }
                      
                      onClickListener(this) //this means current class is implementing onClickListener. 
                      
                        final int[] clickableIds = new int[]{
                                  R.id.easy_mode_button,
                                  R.id.hard_mode_button,
                                  R.id.show_achievements_button,
                                  R.id.show_leaderboards_button,
                                  R.id.sign_in_button,
                                  R.id.sign_out_button
                          };
                      
                          for (int clickableId : clickableIds) {
                              view.findViewById(clickableId).setOnClickListener(this);
                          }
                      
                      onClickListener(this) //this means current class is implementing onClickListener. 
                      

                      "signInSilently(): failure" when trying to sign in to GooglePlay Game Services with LibGDX

                      copy iconCopydownload iconDownload
                        <application
                              android:allowBackup="true"
                              android:icon="@drawable/ic_launcher"
                              android:label="@string/app_name"
                              android:theme="@style/GdxTheme" >
                      
                              <activity
                                  android:name="com.google.android.gms.ads.AdActivity"
                                  android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
                                  android:theme="@android:style/Theme.Translucent" />
                      
                              <activity
                                  android:name="com.harrybanda.blaster.AndroidLauncher"
                                  android:label="@string/app_name" 
                                  android:screenOrientation="portrait"
                                  android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
                                  <intent-filter>
                                      <action android:name="android.intent.action.MAIN" />
                                      <category android:name="android.intent.category.LAUNCHER" />
                                  </intent-filter>
                              </activity>
                      
                            <meta-data android:name="com.google.android.gms.games.APP_ID"
                                       android:value="@string/app_id" />
                      
                            <meta-data android:name="com.google.android.gms.version"
                                       android:value="@integer/google_play_services_version"/>
                          </application>
                      
                      public class AndroidLauncher extends AndroidApplication implements MyServices {
                      
                          private GoogleSignInClient mGoogleSignInClient;
                          private LeaderboardsClient mLeaderboardsClient;
                          private PlayersClient mPlayersClient;
                      
                          private static final String TAG=AndroidLauncher.class.getSimpleName();
                      
                          private static final int RC_SIGN_IN = 9001;
                          private static final int RC_UNUSED = 5001;
                          private static final int RC_LEADERBOARD_UI = 9004;
                      
                          private String greetingMsg="Welcome, ";
                          private boolean greetingDisplayed;
                      
                         @Override
                         protected void onCreate (Bundle savedInstanceState) {
                            super.onCreate(savedInstanceState);
                      
                            greetingDisplayed=false;
                            AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
                            initialize(new GdxGame(this), config);
                      
                            mGoogleSignInClient = GoogleSignIn.getClient(this,
                                  new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN).build());
                      
                         }
                      
                         @Override
                         public boolean isSignedIn() {
                             return GoogleSignIn.getLastSignedInAccount(this) != null;
                         }
                      
                         private void signInSilently() {
                      
                            mGoogleSignInClient.silentSignIn().addOnCompleteListener(this,
                                  new OnCompleteListener<GoogleSignInAccount>() {
                                      @Override
                                      public void onComplete(@NonNull Task<GoogleSignInAccount> task) {
                                          if (task.isSuccessful()) {
                                              greetingMsg="Welcome back, ";
                                              onConnected(task.getResult());
                                          } else {
                                              onDisconnected();
                                          }
                                      }
                                  });
                          }
                      
                          private void onConnected(GoogleSignInAccount googleSignInAccount) {
                      
                             mLeaderboardsClient = Games.getLeaderboardsClient(this, googleSignInAccount);
                             mPlayersClient = Games.getPlayersClient(this, googleSignInAccount);
                      
                              mPlayersClient.getCurrentPlayer()
                                  .addOnCompleteListener(new OnCompleteListener<Player>() {
                                      @Override
                                      public void onComplete(@NonNull Task<Player> task) {
                                          String displayName;
                                          if (task.isSuccessful()) {
                                              displayName = task.getResult().getDisplayName();
                                          } else {
                                              Exception e = task.getException();
                                              handleException(e, getString(R.string.players_exception));
                                              displayName = "???";
                                          }
                      
                                          if(!greetingDisplayed)
                                             welcomeMessage(displayName);
                                      }
                                  });
                          }
                      
                          private void welcomeMessage(String name){
                      
                              Toast toast = Toast.makeText(this, greetingMsg + name, Toast.LENGTH_LONG);
                              toast.setGravity(Gravity.TOP, 0, 0);
                              View view = toast.getView();
                              TextView text = (TextView) view.findViewById(android.R.id.message);
                              toast.show();
                              greetingDisplayed=true;
                          }
                      
                          @Override
                          public void startSignInIntent() {
                              startActivityForResult(mGoogleSignInClient.getSignInIntent(), RC_SIGN_IN);
                          }
                      
                          @Override
                          protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
                              super.onActivityResult(requestCode, resultCode, intent);
                      
                              if (requestCode == RC_SIGN_IN) {
                                Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(intent);
                      
                                try {
                                   GoogleSignInAccount account = task.getResult(ApiException.class);
                                   greetingMsg="Welcome, ";
                                   onConnected(account);
                                } catch (ApiException apiException) {
                                   String message = apiException.getMessage();
                                   if (message == null || message.isEmpty()) {
                                      message = getString(R.string.signin_other_error);
                                   }
                      
                                   onDisconnected();
                                 }
                              }
                          }
                      
                          @Override
                          protected void onResume() {
                             super.onResume();
                             signInSilently();
                         }
                      
                         private void signOut() {
                      
                            if (!isSignedIn()) {
                                Log.w(TAG, "signOut() called, but was not signed in!");
                                return;
                            }
                      
                            mGoogleSignInClient.signOut().addOnCompleteListener(this,
                                  new OnCompleteListener<Void>() {
                                      @Override
                                      public void onComplete(@NonNull Task<Void> task) {
                                          boolean successful = task.isSuccessful();
                                          Log.d(TAG, "signOut(): " + (successful ? "success" : "failed"));
                      
                                          onDisconnected();
                                      }
                                  });
                         }
                      
                          private void onDisconnected() {
                      
                             mLeaderboardsClient = null;
                             mPlayersClient = null;
                          }
                      
                          @Override
                          public void submitScore(int score){
                              if(isSignedIn())
                               mLeaderboardsClient.submitScore(getString(R.string.leaderboard_id), score);
                          }
                      
                          @Override
                          public void showLeaderBoard() {
                             if(isSignedIn())
                                mLeaderboardsClient.getLeaderboardIntent(getString(R.string.leaderboard_id))
                                  .addOnSuccessListener(new OnSuccessListener<Intent>() {
                                      @Override
                                      public void onSuccess(Intent intent) {
                                          startActivityForResult(intent, RC_LEADERBOARD_UI);
                                      }
                                  });
                         }
                      
                         private void handleException(Exception e, String details) {
                             int status = 0;
                      
                            if (e instanceof ApiException) {
                                ApiException apiException = (ApiException) e;
                                status = apiException.getStatusCode();
                            }
                      
                            String message = getString(R.string.status_exception_error, details, status, e);
                      
                            new AlertDialog.Builder(this)
                                  .setMessage(message)
                                  .setNeutralButton(android.R.string.ok, null)
                                  .show();
                          }   
                      }
                      
                      interface MyServices{
                      
                          void startSignInIntent();
                          boolean isSignedIn();
                          void showLeaderBoard();
                          void submitScore(int score);
                      }
                      
                        <application
                              android:allowBackup="true"
                              android:icon="@drawable/ic_launcher"
                              android:label="@string/app_name"
                              android:theme="@style/GdxTheme" >
                      
                              <activity
                                  android:name="com.google.android.gms.ads.AdActivity"
                                  android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
                                  android:theme="@android:style/Theme.Translucent" />
                      
                              <activity
                                  android:name="com.harrybanda.blaster.AndroidLauncher"
                                  android:label="@string/app_name" 
                                  android:screenOrientation="portrait"
                                  android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
                                  <intent-filter>
                                      <action android:name="android.intent.action.MAIN" />
                                      <category android:name="android.intent.category.LAUNCHER" />
                                  </intent-filter>
                              </activity>
                      
                            <meta-data android:name="com.google.android.gms.games.APP_ID"
                                       android:value="@string/app_id" />
                      
                            <meta-data android:name="com.google.android.gms.version"
                                       android:value="@integer/google_play_services_version"/>
                          </application>
                      
                      public class AndroidLauncher extends AndroidApplication implements MyServices {
                      
                          private GoogleSignInClient mGoogleSignInClient;
                          private LeaderboardsClient mLeaderboardsClient;
                          private PlayersClient mPlayersClient;
                      
                          private static final String TAG=AndroidLauncher.class.getSimpleName();
                      
                          private static final int RC_SIGN_IN = 9001;
                          private static final int RC_UNUSED = 5001;
                          private static final int RC_LEADERBOARD_UI = 9004;
                      
                          private String greetingMsg="Welcome, ";
                          private boolean greetingDisplayed;
                      
                         @Override
                         protected void onCreate (Bundle savedInstanceState) {
                            super.onCreate(savedInstanceState);
                      
                            greetingDisplayed=false;
                            AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
                            initialize(new GdxGame(this), config);
                      
                            mGoogleSignInClient = GoogleSignIn.getClient(this,
                                  new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN).build());
                      
                         }
                      
                         @Override
                         public boolean isSignedIn() {
                             return GoogleSignIn.getLastSignedInAccount(this) != null;
                         }
                      
                         private void signInSilently() {
                      
                            mGoogleSignInClient.silentSignIn().addOnCompleteListener(this,
                                  new OnCompleteListener<GoogleSignInAccount>() {
                                      @Override
                                      public void onComplete(@NonNull Task<GoogleSignInAccount> task) {
                                          if (task.isSuccessful()) {
                                              greetingMsg="Welcome back, ";
                                              onConnected(task.getResult());
                                          } else {
                                              onDisconnected();
                                          }
                                      }
                                  });
                          }
                      
                          private void onConnected(GoogleSignInAccount googleSignInAccount) {
                      
                             mLeaderboardsClient = Games.getLeaderboardsClient(this, googleSignInAccount);
                             mPlayersClient = Games.getPlayersClient(this, googleSignInAccount);
                      
                              mPlayersClient.getCurrentPlayer()
                                  .addOnCompleteListener(new OnCompleteListener<Player>() {
                                      @Override
                                      public void onComplete(@NonNull Task<Player> task) {
                                          String displayName;
                                          if (task.isSuccessful()) {
                                              displayName = task.getResult().getDisplayName();
                                          } else {
                                              Exception e = task.getException();
                                              handleException(e, getString(R.string.players_exception));
                                              displayName = "???";
                                          }
                      
                                          if(!greetingDisplayed)
                                             welcomeMessage(displayName);
                                      }
                                  });
                          }
                      
                          private void welcomeMessage(String name){
                      
                              Toast toast = Toast.makeText(this, greetingMsg + name, Toast.LENGTH_LONG);
                              toast.setGravity(Gravity.TOP, 0, 0);
                              View view = toast.getView();
                              TextView text = (TextView) view.findViewById(android.R.id.message);
                              toast.show();
                              greetingDisplayed=true;
                          }
                      
                          @Override
                          public void startSignInIntent() {
                              startActivityForResult(mGoogleSignInClient.getSignInIntent(), RC_SIGN_IN);
                          }
                      
                          @Override
                          protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
                              super.onActivityResult(requestCode, resultCode, intent);
                      
                              if (requestCode == RC_SIGN_IN) {
                                Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(intent);
                      
                                try {
                                   GoogleSignInAccount account = task.getResult(ApiException.class);
                                   greetingMsg="Welcome, ";
                                   onConnected(account);
                                } catch (ApiException apiException) {
                                   String message = apiException.getMessage();
                                   if (message == null || message.isEmpty()) {
                                      message = getString(R.string.signin_other_error);
                                   }
                      
                                   onDisconnected();
                                 }
                              }
                          }
                      
                          @Override
                          protected void onResume() {
                             super.onResume();
                             signInSilently();
                         }
                      
                         private void signOut() {
                      
                            if (!isSignedIn()) {
                                Log.w(TAG, "signOut() called, but was not signed in!");
                                return;
                            }
                      
                            mGoogleSignInClient.signOut().addOnCompleteListener(this,
                                  new OnCompleteListener<Void>() {
                                      @Override
                                      public void onComplete(@NonNull Task<Void> task) {
                                          boolean successful = task.isSuccessful();
                                          Log.d(TAG, "signOut(): " + (successful ? "success" : "failed"));
                      
                                          onDisconnected();
                                      }
                                  });
                         }
                      
                          private void onDisconnected() {
                      
                             mLeaderboardsClient = null;
                             mPlayersClient = null;
                          }
                      
                          @Override
                          public void submitScore(int score){
                              if(isSignedIn())
                               mLeaderboardsClient.submitScore(getString(R.string.leaderboard_id), score);
                          }
                      
                          @Override
                          public void showLeaderBoard() {
                             if(isSignedIn())
                                mLeaderboardsClient.getLeaderboardIntent(getString(R.string.leaderboard_id))
                                  .addOnSuccessListener(new OnSuccessListener<Intent>() {
                                      @Override
                                      public void onSuccess(Intent intent) {
                                          startActivityForResult(intent, RC_LEADERBOARD_UI);
                                      }
                                  });
                         }
                      
                         private void handleException(Exception e, String details) {
                             int status = 0;
                      
                            if (e instanceof ApiException) {
                                ApiException apiException = (ApiException) e;
                                status = apiException.getStatusCode();
                            }
                      
                            String message = getString(R.string.status_exception_error, details, status, e);
                      
                            new AlertDialog.Builder(this)
                                  .setMessage(message)
                                  .setNeutralButton(android.R.string.ok, null)
                                  .show();
                          }   
                      }
                      
                      interface MyServices{
                      
                          void startSignInIntent();
                          boolean isSignedIn();
                          void showLeaderBoard();
                          void submitScore(int score);
                      }
                      
                        <application
                              android:allowBackup="true"
                              android:icon="@drawable/ic_launcher"
                              android:label="@string/app_name"
                              android:theme="@style/GdxTheme" >
                      
                              <activity
                                  android:name="com.google.android.gms.ads.AdActivity"
                                  android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
                                  android:theme="@android:style/Theme.Translucent" />
                      
                              <activity
                                  android:name="com.harrybanda.blaster.AndroidLauncher"
                                  android:label="@string/app_name" 
                                  android:screenOrientation="portrait"
                                  android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
                                  <intent-filter>
                                      <action android:name="android.intent.action.MAIN" />
                                      <category android:name="android.intent.category.LAUNCHER" />
                                  </intent-filter>
                              </activity>
                      
                            <meta-data android:name="com.google.android.gms.games.APP_ID"
                                       android:value="@string/app_id" />
                      
                            <meta-data android:name="com.google.android.gms.version"
                                       android:value="@integer/google_play_services_version"/>
                          </application>
                      
                      public class AndroidLauncher extends AndroidApplication implements MyServices {
                      
                          private GoogleSignInClient mGoogleSignInClient;
                          private LeaderboardsClient mLeaderboardsClient;
                          private PlayersClient mPlayersClient;
                      
                          private static final String TAG=AndroidLauncher.class.getSimpleName();
                      
                          private static final int RC_SIGN_IN = 9001;
                          private static final int RC_UNUSED = 5001;
                          private static final int RC_LEADERBOARD_UI = 9004;
                      
                          private String greetingMsg="Welcome, ";
                          private boolean greetingDisplayed;
                      
                         @Override
                         protected void onCreate (Bundle savedInstanceState) {
                            super.onCreate(savedInstanceState);
                      
                            greetingDisplayed=false;
                            AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
                            initialize(new GdxGame(this), config);
                      
                            mGoogleSignInClient = GoogleSignIn.getClient(this,
                                  new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN).build());
                      
                         }
                      
                         @Override
                         public boolean isSignedIn() {
                             return GoogleSignIn.getLastSignedInAccount(this) != null;
                         }
                      
                         private void signInSilently() {
                      
                            mGoogleSignInClient.silentSignIn().addOnCompleteListener(this,
                                  new OnCompleteListener<GoogleSignInAccount>() {
                                      @Override
                                      public void onComplete(@NonNull Task<GoogleSignInAccount> task) {
                                          if (task.isSuccessful()) {
                                              greetingMsg="Welcome back, ";
                                              onConnected(task.getResult());
                                          } else {
                                              onDisconnected();
                                          }
                                      }
                                  });
                          }
                      
                          private void onConnected(GoogleSignInAccount googleSignInAccount) {
                      
                             mLeaderboardsClient = Games.getLeaderboardsClient(this, googleSignInAccount);
                             mPlayersClient = Games.getPlayersClient(this, googleSignInAccount);
                      
                              mPlayersClient.getCurrentPlayer()
                                  .addOnCompleteListener(new OnCompleteListener<Player>() {
                                      @Override
                                      public void onComplete(@NonNull Task<Player> task) {
                                          String displayName;
                                          if (task.isSuccessful()) {
                                              displayName = task.getResult().getDisplayName();
                                          } else {
                                              Exception e = task.getException();
                                              handleException(e, getString(R.string.players_exception));
                                              displayName = "???";
                                          }
                      
                                          if(!greetingDisplayed)
                                             welcomeMessage(displayName);
                                      }
                                  });
                          }
                      
                          private void welcomeMessage(String name){
                      
                              Toast toast = Toast.makeText(this, greetingMsg + name, Toast.LENGTH_LONG);
                              toast.setGravity(Gravity.TOP, 0, 0);
                              View view = toast.getView();
                              TextView text = (TextView) view.findViewById(android.R.id.message);
                              toast.show();
                              greetingDisplayed=true;
                          }
                      
                          @Override
                          public void startSignInIntent() {
                              startActivityForResult(mGoogleSignInClient.getSignInIntent(), RC_SIGN_IN);
                          }
                      
                          @Override
                          protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
                              super.onActivityResult(requestCode, resultCode, intent);
                      
                              if (requestCode == RC_SIGN_IN) {
                                Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(intent);
                      
                                try {
                                   GoogleSignInAccount account = task.getResult(ApiException.class);
                                   greetingMsg="Welcome, ";
                                   onConnected(account);
                                } catch (ApiException apiException) {
                                   String message = apiException.getMessage();
                                   if (message == null || message.isEmpty()) {
                                      message = getString(R.string.signin_other_error);
                                   }
                      
                                   onDisconnected();
                                 }
                              }
                          }
                      
                          @Override
                          protected void onResume() {
                             super.onResume();
                             signInSilently();
                         }
                      
                         private void signOut() {
                      
                            if (!isSignedIn()) {
                                Log.w(TAG, "signOut() called, but was not signed in!");
                                return;
                            }
                      
                            mGoogleSignInClient.signOut().addOnCompleteListener(this,
                                  new OnCompleteListener<Void>() {
                                      @Override
                                      public void onComplete(@NonNull Task<Void> task) {
                                          boolean successful = task.isSuccessful();
                                          Log.d(TAG, "signOut(): " + (successful ? "success" : "failed"));
                      
                                          onDisconnected();
                                      }
                                  });
                         }
                      
                          private void onDisconnected() {
                      
                             mLeaderboardsClient = null;
                             mPlayersClient = null;
                          }
                      
                          @Override
                          public void submitScore(int score){
                              if(isSignedIn())
                               mLeaderboardsClient.submitScore(getString(R.string.leaderboard_id), score);
                          }
                      
                          @Override
                          public void showLeaderBoard() {
                             if(isSignedIn())
                                mLeaderboardsClient.getLeaderboardIntent(getString(R.string.leaderboard_id))
                                  .addOnSuccessListener(new OnSuccessListener<Intent>() {
                                      @Override
                                      public void onSuccess(Intent intent) {
                                          startActivityForResult(intent, RC_LEADERBOARD_UI);
                                      }
                                  });
                         }
                      
                         private void handleException(Exception e, String details) {
                             int status = 0;
                      
                            if (e instanceof ApiException) {
                                ApiException apiException = (ApiException) e;
                                status = apiException.getStatusCode();
                            }
                      
                            String message = getString(R.string.status_exception_error, details, status, e);
                      
                            new AlertDialog.Builder(this)
                                  .setMessage(message)
                                  .setNeutralButton(android.R.string.ok, null)
                                  .show();
                          }   
                      }
                      
                      interface MyServices{
                      
                          void startSignInIntent();
                          boolean isSignedIn();
                          void showLeaderBoard();
                          void submitScore(int score);
                      }
                      

                      How to trigger onActivityResult

                      copy iconCopydownload iconDownload
                      handler.postDelayed(new Runnable()
                              {
                                  @Override
                                  public void run() {
                                      if (mSYGameOn>0) {
                                          finishActivity(RC_WAITING_ROOM);
                                      }
                                  }
                              }, 30000);
                      

                      Community Discussions

                      Trending Discussions on android-basic-samples
                      • Google play games services : Saved games, creating a new snapshot
                      • Turn Based Game player receives its own data without opponent calling takeTurn
                      • Google Play Games API returns SIGN_IN_REQUIRED
                      • Implementing a leaderboard in a LibGDX game
                      • Leaderboard signin using android basic samples fails with com.google.android.gms.common.api.ApiException: 4:
                      • integrating libGDX Game with google play games Leaderboards wit help of android basic examples
                      • LibGDX: How to Implement Google Play Game Services?
                      • What does "for (int clickableId : clickableIds)" do?
                      • "signInSilently(): failure" when trying to sign in to GooglePlay Game Services with LibGDX
                      • android google game service - Server control
                      Trending Discussions on android-basic-samples

                      QUESTION

                      Google play games services : Saved games, creating a new snapshot

                      Asked 2019-Jul-10 at 09:30

                      I'm following the google developers guide on how to setup saved games in my game, when i reach the part where you create a snapshot to store your data, the guide doesn't specify what to do.

                      Also i checked the sample code provided here https://github.com/gguuss/android-basic-samples/tree/master/BasicSamples/CollectAllTheStars2

                      but some of the methods used are marked as deprecated, and they didn't update the code since 5 years ago

                      private String mCurrentSaveName = "snapshotTemp";
                      
                      /**
                       * This callback will be triggered after you call startActivityForResult from the
                       * showSavedGamesUI method.
                       */
                      @Override
                      protected void onActivityResult(int requestCode, int resultCode,
                                                      Intent intent) {
                        if (intent != null) {
                          if (intent.hasExtra(SnapshotsClient.EXTRA_SNAPSHOT_METADATA)) {
                            // Load a snapshot.
                            SnapshotMetadata snapshotMetadata =
                                intent.getParcelableExtra(SnapshotsClient.EXTRA_SNAPSHOT_METADATA);
                            mCurrentSaveName = snapshotMetadata.getUniqueName();
                      
                            // Load the game data from the Snapshot
                            // ...
                          } else if (intent.hasExtra(SnapshotsClient.EXTRA_SNAPSHOT_NEW)) {
                            // Create a new snapshot named with a unique string
                            String unique = new BigInteger(281, new Random()).toString(13);
                            mCurrentSaveName = "snapshotTemp-" + unique;
                      
                            // Create the new snapshot
                            // ...
                          }
                        }
                      }
                      

                      Can anyone help me ? and what to be done near //create the new snapshot comment ?

                      ANSWER

                      Answered 2019-Jul-10 at 09:30

                      After much research i found out how to do it, before you do this your player must be signed in

                      //the data you want to save must be in bytes
                      byte[] bytearray;
                      //name of the snapshot
                      private String currentSave="snapshot"+1235;
                      
                      private void executeSaving(){
                      
                          // get the snapshoClient
                          SnapshotsClient snapshotsClient= Games.getSnapshotsClient(this,account);
                      
                          // to save a game
                          snapshotsClient.open(currentSave,true).addOnCompleteListener(task -> {
                      
                              Snapshot snapshot =task.getResult().getData();
                      
                              if (snapshot != null){
                                  //call of the method writeSnapshot params : the snapshot and the data we 
                                  //want to save with a description
                                  writeSnapshot(snapshot,bytearray,"first description").addOnCompleteListener(task1 -> {
                      
                                      if(task1.isSuccessful()){
                                          Toast.makeText(getApplicationContext(),"Succesful",Toast.LENGTH_SHORT).show();
                                      }else {
                                          Log.e("ERR",""+task1.getException());
                                      }
                                  });
                              }
                          });
                      }
                      
                      private Task<SnapshotMetadata> writeSnapshot(Snapshot snapshot ,byte[] bytearray,String desc){
                      
                          //write your data in the snapshot
                          snapshot.getSnapshotContents().writeBytes(bytearray);
                      
                          SnapshotMetadataChange snapshotMetadata = new SnapshotMetadataChange.Builder().setDescription(desc).build();
                      
                          SnapshotsClient snapshotsClient=Games.getSnapshotsClient(this,account);
                      
                          //commit and close to send the new changes to google play games services
                          return snapshotsClient.commitAndClose(snapshot,snapshotMetadata);
                      }
                      

                      Source https://stackoverflow.com/questions/56955983

                      Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                      Vulnerabilities

                      No vulnerabilities reported

                      Install android-basic-samples

                      You can download it from GitHub.
                      You can use android-basic-samples like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the android-basic-samples component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

                      Support

                      For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

                      DOWNLOAD this Library from

                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                      over 430 million Knowledge Items
                      Find more libraries
                      Reuse Solution Kits and Libraries Curated by Popular Use Cases
                      Explore Kits

                      Save this library and start creating your kit

                      Explore Related Topics

                      Share this Page

                      share link
                      Consider Popular Android Libraries
                      Try Top Libraries by playgameservices
                      Compare Android Libraries with Highest Support
                      Compare Android Libraries with Highest Quality
                      Compare Android Libraries with Highest Security
                      Compare Android Libraries with Permissive License
                      Compare Android Libraries with Highest Reuse
                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                      over 430 million Knowledge Items
                      Find more libraries
                      Reuse Solution Kits and Libraries Curated by Popular Use Cases
                      Explore Kits

                      Save this library and start creating your kit

                      • © 2022 Open Weaver Inc.