Repository: googlesamples/easygoogle Branch: master Commit: 6660e3f51b6b Files: 48 Total size: 136.6 KB Directory structure: gitextract_vqm55ndh/ ├── .gitignore ├── LICENSE ├── README.md ├── RELEASENOTES.md ├── app/ │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── pub/ │ │ └── devrel/ │ │ └── easygoogle/ │ │ └── sample/ │ │ ├── MainActivity.java │ │ ├── MainFragmentActivity.java │ │ └── MessagingService.java │ └── res/ │ ├── layout/ │ │ └── activity_main.xml │ ├── values/ │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── values-w820dp/ │ └── dimens.xml ├── build.gradle ├── easygoogle/ │ ├── .gitignore │ ├── bintray.gradle │ ├── build.gradle │ ├── constants.gradle │ ├── maven.gradle │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── pub/ │ │ └── devrel/ │ │ └── easygoogle/ │ │ ├── FragmentUtils.java │ │ ├── Google.java │ │ ├── gac/ │ │ │ ├── AppInvites.java │ │ │ ├── AppInvitesReferralReceiver.java │ │ │ ├── GacFragment.java │ │ │ ├── GacModule.java │ │ │ ├── SignIn.java │ │ │ └── SmartLock.java │ │ └── gcm/ │ │ ├── EasyMessageService.java │ │ ├── GCMUtils.java │ │ ├── IDListenerService.java │ │ ├── IDRegisterService.java │ │ ├── MessageListenerService.java │ │ ├── MessageSenderService.java │ │ ├── Messaging.java │ │ ├── MessagingFragment.java │ │ └── PubSubService.java │ └── res/ │ └── values/ │ └── strings.xml ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .gradle /local.properties /.idea/workspace.xml /.idea/libraries .DS_Store /build .idea/ *.iml build/ /local.properties /captures google-services.json ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # EasyGoogle ## Project status ![status: inactive](https://img.shields.io/badge/status-inactive-red.svg) This project is no longer actively maintained, and remains here as an archive of this work. EasyGoogle was created as an experimental improvement to the developer experience for certain Google APIs. In the time since its creation, most of these APIs have improved (and many in ways that resemble EasyGoogle). For this reason it no longer makes sense to maintain this library. Thank you to everyone who submitted issues or gave feedback, your thoughts influenced API development at Google. ## Introduction EasyGoogle is a wrapper library to simplify basic integrations with Google Play Services. The library wraps the following APIs (for now): * [Google Sign-In](https://developers.google.com/identity/sign-in/android/) * [Google Cloud Messaging](https://developers.google.com/cloud-messaging/) * [Google App Invites](https://developers.google.com/app-invites/) * [Google SmartLock for Passwords](https://developers.google.com/identity/smartlock-passwords/android/) ## Installation EasyGoogle is installed by adding the following dependency to your `build.gradle` file: dependencies { compile 'pub.devrel:easygoogle:0.2.5+' } ## Usage ### Enabling Services Before you begin, visit [this page](https://developers.google.com/mobile/add) to select Google services and add them to your Android app. Make sure to enable any services you plan to use and follow all of the steps, including modifying your `build.gradle` files to enable the `google-services` plugin. Once you have a `google-services.json` file in the proper place you can proceed to use EasyGoogle. ### Basic EasyGoogle makes use of `Fragments` to manage the lifecycle of the `GoogleApiClient`, so any Activity which uses EasyGoogle must extend `FragmentActivity`. All interaction with EasyGoogle is through the `Google` class, which is instantiated like this: ```java public class MainActivity extends AppCompatActivity { private Google mGoogle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGoogle = new Google.Builder(this).build(); } } ``` Of course, instantiating a `Google` object like this won't do anything at all, you need to enable features individually. ### Sign-In To enable Google Sign-In, call the appropriate method on `Google.Builder` and implement the `SignIn.SignInListener` interface: ```java public class MainActivity extends AppCompatActivity implements SignIn.SignInListener { private Google mGoogle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // This is optional, pass 'null' if no ID token is required. String serverClientId = getString(R.string.default_web_client_id); mGoogle = new Google.Builder(this) .enableSignIn(this, serverClientId) .build(); } @Override public void onSignedIn(GoogleSignInAccount account) { // Sign in was successful. } @Override public void onSignedOut() { // Sign out was successful. } @Override public void onSignInFailed() { // Sign in failed for some reason and should not be attempted again // unless the user requests it. } } ``` Then, use the `SignIn` object from `mGoogle.getSignIn()` to access API methods like `SignIn#getCurrentUser()`, `SignIn#signIn`, and `SignIn#signOut`. ### Cloud Messaging To enable Cloud Messaging, you will have to implement a simple `Service` in your application. First, pick a unique permission name and make the following string resource in your `strings.xml` file. It is important to pick a unique name: ```xml your.unique.gcm.permission.name.here ``` Next, add the following to your `AndroidManifest.xml` inside the `application` tag, making sure that the value of the `android:permission` element is the same value you specified in your `strings.xml` file above: ```xml ``` Next, add the following permission to your `AndroidManifest.xml` file before the `application` tag, replacing `` with your Android package name: ```xml ``` Then implement a class called `MessagingService` that extends `EasyMessageService`. Below is one example of such a class: ```java public class MessagingService extends EasyMessageService { @Override public void onMessageReceived(String from, Bundle data) { // If there is a running Activity that implements MessageListener, it should handle // this message. if (!forwardToListener(from, data)) { // There is no active MessageListener to get this, I should fire a notification with // a PendingIntent to an activity that can handle this. PendingIntent pendingIntent = createMessageIntent(from, data, MainActivity.class); Notification notif = new NotificationCompat.Builder(this) .setContentTitle("Message from: " + from) .setContentText(data.getString("message")) .setSmallIcon(R.mipmap.ic_launcher) .setContentIntent(pendingIntent) .setAutoCancel(true) .build(); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0, notif); } } @Override public void onNewToken(String token) { // Send a registration message to the server with our new token String senderId = getString(R.string.gcm_defaultSenderId); sendRegistrationMessage(senderId, token); } } ``` Note the use of the helper methods `forwardToListener` and `createMessageIntent`, which make it easier for you to either launch an Activity or create a Notification to handle the message. The `forwardToListener` method checks to see if there is an Activity that implements `Messaging.MessagingListener` in the foreground. If there is, it sends the GCM message to the Activity to be handled. To implement `Messaging.MessagingListener`, call the appropriate method on `Google.Builder` in your `Activity` and implement the interface: ```java public class MainActivity extends AppCompatActivity implements Messaging.MessagingListener { private Google mGoogle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGoogle = new Google.Builder(this) .enableMessaging(this, getString(R.string.gcm_defaultSenderId)) .build(); } @Override public void onMessageReceived(String from, Bundle message) { // GCM message received. } } ``` Then, use the `Messaging` object from `mGoogle.getMessaging()` to access API methodslike `Messaging#send`. ### App Invites To enable App Invites, call the appropriate method on `Google.Builder` and implement the `AppInvites.AppInviteListener` interface: ```java public class MainActivity extends AppCompatActivity implements AppInvites.AppInviteListener { private Google mGoogle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGoogle = new Google.Builder(this) .enableAppInvites(this) .build(); } @Override public void onInvitationReceived(String invitationId, String deepLink) { // Invitation recieved in the app. } @Override public void onInvitationsSent(String[] ids) { // The user selected contacts and invitations sent successfully. } @Override public void onInvitationsFailed() { // The user either canceled sending invitations or they failed to // send due to some configuration error. } } ``` Then, use the `AppInvites` object from `mGoogle.getAppInvites()` to access API methods like `AppInvites#sendInvitation`. ### SmartLock for Passwords To enable Smart Lock for Passwords, call the appropriate method on `Google.Builder` and implement the `SmartLock.SmartLockListener` interface: ```java public class MainActivity extends AppCompatActivity implements SmartLock.SmartLockListener { private Google mGoogle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGoogle = new Google.Builder(this) .enableSmartLock(this) .build(); } @Override public void onCredentialRetrieved(Credential credential) { // Successfully retrieved a Credential for the current device user. } @Override public void onShouldShowCredentialPicker() { // In order to retrieve a Credential, the app must show the picker dialog // using the SmartLock#showCredentialPicker() method. } @Override public void onCredentialRetrievalFailed() { // The user has no stored credentials, or the retrieval operation failed or // was canceled. } } ``` Then, use the `SmartLock` object from `mGoogle.getSmartLock()` to access API methods like `SmartLock#getCredentials()` and `SmartLock#save()`. ### Advanced Usage If you would like to perform some action using one of the enabled Google services but it is not properly wrapped by the EasyGoogle library, just call `Google#getGoogleApiClient()` to get access to the underlying `GoogleApiClient` held by the `Google` object. ================================================ FILE: RELEASENOTES.md ================================================ # 0.2.1 * Added new module for SmartLock for Passwords. # 0.2.0 * Upgraded to Google Play Services version 8.3.0. * Upgraded gradle plugin version, target SDK version, and appcompat version. * Updated SignIn to use new `GoogleSignIn` API and added the method `SignIn#getCurrentUser`. * Removed dependency on `play-services-plus` and replaced all instances of `Person` with `GoogleSignInAccount` (breaking interface change). # 0.1.0 * Initial Release ================================================ FILE: app/.gitignore ================================================ /build ================================================ FILE: app/build.gradle ================================================ apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' android { compileSdkVersion 23 buildToolsVersion "23.0.2" defaultConfig { applicationId "pub.devrel.easygoogle.sample" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } repositories { mavenLocal() } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.1.1' // compile 'pub.devrel:easygoogle:+' compile project(':easygoogle') } ================================================ FILE: app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /usr/local/Android/Sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/java/pub/devrel/easygoogle/sample/MainActivity.java ================================================ /* * Copyright Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pub.devrel.easygoogle.sample; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.TextView; import com.google.android.gms.auth.api.credentials.Credential; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import pub.devrel.easygoogle.Google; import pub.devrel.easygoogle.gac.AppInvites; import pub.devrel.easygoogle.gac.SignIn; import pub.devrel.easygoogle.gac.SmartLock; import pub.devrel.easygoogle.gcm.Messaging; /** * Simple Activity demonstrating how to use the EasyGoogle library to quickly integrate * Sign-In, App Invites, Google Cloud Messaging, and SmartLock for Passwords. */ public class MainActivity extends AppCompatActivity implements SignIn.SignInListener, Messaging.MessagingListener, AppInvites.AppInviteListener, SmartLock.SmartLockListener, View.OnClickListener { public static String TAG = "sample.MainActivity"; private Google mGoogle; // SmartLock data/fields private Credential mCredential; private EditText mUsernameField; private EditText mPasswordField; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize the Google object with access to Cloud Messaging, Sign-In, and App Invites. // All APIs are accessed through the Google object and the result of asynchronous operations // are returned through API-specific listener classes like {@link SignIn.SignInListener}. mGoogle = new Google.Builder(this) .enableMessaging(this, getString(R.string.gcm_defaultSenderId)) .enableSignIn(this, null) .enableAppInvites(this) .enableSmartLock(this) .build(); // Inject sign-in button, automatically configured to initiate sign-in when clicked. mGoogle.getSignIn().createSignInButton(this, (ViewGroup) findViewById(R.id.layout_sign_in)); // Click listeners for buttons findViewById(R.id.send_message_button).setOnClickListener(this); findViewById(R.id.sign_out_button).setOnClickListener(this); findViewById(R.id.send_invites_button).setOnClickListener(this); findViewById(R.id.button_smartlock_load).setOnClickListener(this); findViewById(R.id.button_smartlock_save).setOnClickListener(this); findViewById(R.id.button_smartlock_delete).setOnClickListener(this); // Other views mUsernameField = ((EditText) findViewById(R.id.field_smartlock_username)); mPasswordField = ((EditText) findViewById(R.id.field_smartlock_password)); } @Override public void onStart() { super.onStart(); // Subscribe to the "easygoogle" topic mGoogle.getMessaging().subscribeTo("/topics/easygoogle"); } @Override public void onSignedIn(GoogleSignInAccount account) { Log.d(TAG, "onSignedIn:" + account.getEmail()); ((TextView) findViewById(R.id.sign_in_status)).setText( getString(R.string.status_signed_in_fmt, account.getDisplayName(), account.getEmail())); } @Override public void onSignedOut() { ((TextView) findViewById(R.id.sign_in_status)).setText(R.string.status_signed_out); } @Override public void onSignInFailed() { ((TextView) findViewById(R.id.sign_in_status)).setText(R.string.status_sign_in_failed); } @Override public void onMessageReceived(String from, Bundle message) { ((TextView) findViewById(R.id.messaging_status)).setText( getString(R.string.status_message_fmt, from)); } @Override public void onInvitationReceived(String invitationId, String deepLink) { ((TextView) findViewById(R.id.app_invites_status)).setText( getString(R.string.status_invitation_fmt, invitationId, deepLink)); } @Override public void onInvitationsSent(String[] ids) { ((TextView) findViewById(R.id.app_invites_status)).setText( getString(R.string.status_invitation_sent_fmt, ids.length)); } @Override public void onInvitationsFailed() { ((TextView) findViewById(R.id.app_invites_status)).setText(R.string.status_invitation_failed); } @Override public void onCredentialRetrieved(Credential credential) { ((TextView) findViewById(R.id.smartlock_status)).setText(R.string.status_credential_retrieved); mCredential = credential; mUsernameField.setText(credential.getId()); mPasswordField.setText(credential.getPassword()); } @Override public void onShouldShowCredentialPicker() { mGoogle.getSmartLock().showCredentialPicker(); } @Override public void onCredentialRetrievalFailed() { ((TextView) findViewById(R.id.smartlock_status)).setText(R.string.status_credential_failed); mUsernameField.setText(null); mPasswordField.setText(null); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.sign_out_button: // Sign out with Google mGoogle.getSignIn().signOut(); break; case R.id.send_message_button: // Send a GCM message Bundle b = new Bundle(); b.putString("message", "I am a banana!"); mGoogle.getMessaging().send(b); break; case R.id.send_invites_button: // Send App Invites mGoogle.getAppInvites().sendInvitation( "Title", "Message", Uri.parse("http://example.com/id/12345")); break; case R.id.button_smartlock_load: // Begin loading Credentials mGoogle.getSmartLock().getCredentials(); break; case R.id.button_smartlock_save: // Save Credential String id = mUsernameField.getText().toString(); String password = mPasswordField.getText().toString(); mGoogle.getSmartLock().save(id, password); ((TextView) findViewById(R.id.smartlock_status)).setText(null); mUsernameField.setText(null); mPasswordField.setText(null); break; case R.id.button_smartlock_delete: // Delete Credential and clear fields if (mCredential != null) { mGoogle.getSmartLock().delete(mCredential); mCredential = null; ((TextView) findViewById(R.id.smartlock_status)).setText(null); mUsernameField.setText(null); mPasswordField.setText(null); } break; } } } ================================================ FILE: app/src/main/java/pub/devrel/easygoogle/sample/MainFragmentActivity.java ================================================ package pub.devrel.easygoogle.sample; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import pub.devrel.easygoogle.Google; import pub.devrel.easygoogle.gac.SignIn; import pub.devrel.easygoogle.gcm.Messaging; /** * Activity for demonstrating the use of EasyGoogle in Fragments. */ public class MainFragmentActivity extends AppCompatActivity implements Messaging.MessagingListener { private static final String TAG = "MainFragmentActivity"; private Google mGoogle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate"); mGoogle = new Google.Builder(this) .enableMessaging(this, getString(R.string.gcm_defaultSenderId)) .build(); getSupportFragmentManager().beginTransaction() .add(android.R.id.content, new EasyGoogleFragment()) .commit(); } @Override public void onStart() { super.onStart(); mGoogle.getMessaging().subscribeTo("/topics/easygoogle-test"); } @Override public void onMessageReceived(String from, Bundle message) { Log.d(TAG, "onMessageReceived:" + from); } /** * Fragment that hosts Sign In. */ public static class EasyGoogleFragment extends Fragment implements SignIn.SignInListener { private static final String TAG = "EasyGoogleFragment"; private Google mGoogle; public EasyGoogleFragment() {} @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.d(TAG, "onActivityCreated"); mGoogle = new Google.Builder(getActivity()) .enableSignIn(this, null) .build(); Log.d(TAG, "onActivityCreated:isSignedIn:" + isSignedIn()); } @Override public void onStart() { super.onStart(); Log.d(TAG, "onStart"); Log.d(TAG, "onStart:isSignedIn:" + isSignedIn()); if (!isSignedIn()) { mGoogle.getSignIn().signIn(); } } private boolean isSignedIn() { // The GoogleApiClient is only created on onActivityCreated of GacFragment, which is // not guaranteed to happen before or after this fragment is created if (mGoogle.getGoogleApiClient() == null) { Log.e(TAG, "isSignedIn: mGoogle.getGoogleApiClient() == null"); return false; } return (mGoogle.getSignIn().isSignedIn()); } @Override public void onSignedIn(GoogleSignInAccount account) { Log.d(TAG, "onSignedIn:" + account); } @Override public void onSignInFailed() { Log.d(TAG, "onSignInFailed"); } @Override public void onSignedOut() { Log.d(TAG, "onSignedOut"); } } } ================================================ FILE: app/src/main/java/pub/devrel/easygoogle/sample/MessagingService.java ================================================ package pub.devrel.easygoogle.sample; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.util.Log; import pub.devrel.easygoogle.gcm.EasyMessageService; /** * Background service to receive GCM events on behalf of the application. */ public class MessagingService extends EasyMessageService { public static final String TAG = "MessagingService"; @Override public void onMessageReceived(String from, Bundle data) { Log.d(TAG, "onMessageReceived:" + from + ":" + data); // If there is a running Activity that implements MessageListener, it should handle // this message. if (!forwardToListener(from, data)) { // There is no active MessageListener to get this, I should fire a notification with // a PendingIntent to an activity that can handle this Log.d(TAG, "onMessageReceived: no active listeners"); PendingIntent pendingIntent = createMessageIntent(from, data, MainActivity.class); Notification notif = new NotificationCompat.Builder(this) .setContentTitle("Message from: " + from) .setContentText(data.getString("message")) .setSmallIcon(R.mipmap.ic_launcher) .setContentIntent(pendingIntent) .setAutoCancel(true) .build(); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0, notif); } } @Override public void onNewToken(String token) { Log.d(TAG, "onNewToken:" + token); // When a new token is received, send it upstream so that the server knows about this // client and can send downstream messages properly. This should happen infrequently. String senderId = getString(R.string.gcm_defaultSenderId); sendRegistrationMessage(senderId, token); } } ================================================ FILE: app/src/main/res/layout/activity_main.xml ================================================