Google APIs的一個簡單Java封裝庫:easygoogle

nyyb 8年前發布 | 9K 次閱讀 Java開發 easygoogle

EasyGoogle是一個封裝庫簡化了與Google Play Services的基礎交互。這個庫封裝了以下APIs當前:

安裝

EasyGoogle is installed by adding the following dependency to yourbuild.gradlefile:

dependencies {
  compile 'pub.devrel:easygoogle:0.2.1+'
}

Enabling Services

Before you begin, visit this page 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 yourbuild.gradlefiles to enable thegoogle-servicesplugin.

Once you have agoogle-services.jsonfile in the proper place you can proceed to use EasyGoogle.

Basic

EasyGoogle makes use ofFragmentsto manage the lifecycle of theGoogleApiClient, so any Activity which uses EasyGoogle must extendFragmentActivity.

All interaction with EasyGoogle is through theGoogleclass, which is instantiated like this:

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 aGoogleobject 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 onGoogle.Builderand implement theSignIn.SignInListenerinterface:

 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);

     mGoogle = new Google.Builder(this)
       .enableSignIn(this)
       .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 theSignInobject frommGoogle.getSignIn()to access API methods likeSignIn#getCurrentUser(),SignIn#signIn, andSignIn#signOut.

Cloud Messaging

To enable Cloud Messaging, you will have to implement a simpleServicein your application.

First, pick a unique permission name and make the following string resource in yourstrings.xmlfile. It is important to pick a unique name:

<string name="gcm_permission">your.unique.gcm.permission.name.here</string>

Next, add the following to yourAndroidManifest.xmlinside theapplicationtag:

 <!-- This allows the app to receive GCM through EasyGoogle -->
 <service
     android:name=".MessagingService"
     android:enabled="true"
     android:exported="false"
     android:permission="@string/gcm_permission" />

Then implement a class calledMessagingServicethat extendsEasyMessageService. Below is one example of such a class:

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 methodsforwardToListenerandcreateMessageIntent, which make it easier for you to either launch an Activity or create a Notification to handle the message.

TheforwardToListenermethod checks to see if there is an Activity that implementsMessaging.MessagingListenerin the foreground. If there is, it sends the GCM message to the Activity to be handled. To implementMessaging.MessagingListener, call the appropriate method onGoogle.Builderin yourActivityand implement the interface:

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 theMessagingobject frommGoogle.getMessaging()to access API methodslikeMessaging#send.

App Invites

To enable App Invites, call the appropriate method onGoogle.Builderand implement theAppInvites.AppInviteListenerinterface:

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 theAppInvitesobject frommGoogle.getAppInvites()to access API methods likeAppInvites#sendInvitation.

SmartLock for Passwords

To enable Smart Lock for Passwords, call the appropriate method onGoogle.Builderand implement theSmartLock.SmartLockListenerinterface:

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 theSmartLockobject frommGoogle.getSmartLock()to access API methods likeSmartLock#getCredentials()andSmartLock#save(). 

項目主頁:http://www.baiduhome.net/lib/view/home/1449892875254

 本文由用戶 nyyb 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!