RxSmartLock


Source link: http://shlmlkzdh.github.io/RxSmartLock

RxSmartLock

Reactive extension for Google's Smart Lock for Passwords API.

Introduction

Sebastiano Poggi has written a fantastic blog post on Smart Lock. Read it here.

Usage

In order to use RxSmartLock, create a SmartLock object using the SmartLock.Builder class in the onCreate method of your Activity:

public class MainActivity extends AppCompatActivity {

private SmartLock mSmartLock;

@Override
  protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

 mSmartLock = new SmartLock.Builder(this)

  .setAccountTypes(IdentityProviders.GOOGLE, IdentityProviders.FACEBOOK) // Use the constants defined in IdentityProviders to specify commonly-used sign-in providers.

  .setPasswordLoginSupported(true) // Used for password-based sign-in.

  .build();

}
  
}

Now you are ready to use RxSmartLock.

Retrieve a User's Stored Credentials

Automatically sign users into your app by using the Credentials API to request and retrieve stored credentials for your users.

To request stored credentials, call the retrieveCredential() method on the SmartLock object that you created from anywhere in your Activity. This method returns an observabale Observable<Credential> which you can subscribe to:

mSubscription = mSmartLock.retrieveCredential().subscribe(new Subscriber<Credential>() {

@Override
  public void onCompleted() {

}

@Override
  public void onError(Throwable e) {

 // Handle unsuccessful and incomplete credential requests.

if (e instanceof StatusException) {

 Status status = ((StatusException) e).getStatus();

 if (status.hasResolution()) {

  // Prompt the user to choose a saved credential; do not show the hint selector.

  try {

status.startResolutionForResult(MainActivity.this, CREDENTIAL_REQUEST_RC);

  
}
 catch (IntentSender.SendIntentException e1) {

Log.e(TAG, "STATUS: Failed to send resolution.");

  
}

 
}
 else {

  // The user must create an account or sign in manually.

  Log.e(TAG, "STATUS: Unsuccessful credential request.");

 
}

}

}

@Override
  public void onNext(Credential credential) {

// On a successful credential request, use the resulting Credential object to complete the user's sign-in to your app.
  
}
  
}
);

When user input is required to select a credential, the Status.hasResolution() method returns true. In this case, call the status object's startResolutionForResult() method to prompt the user to choose an account. Then, retrieve the user's chosen credentials from the activity's onActivityResult() method by calling the retrieveCredentialFromIntent(Intent) method on the SmartLock object that you created. This method returns an observabale Observable<Credential> which you can again subscribe to:

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {

  super.onActivityResult(requestCode, resultCode, data);

  if (requestCode == CREDENTIAL_REQUEST_RC) {

if (resultCode == RESULT_OK) {

 mSmartLock.retrieveCredentialFromIntent(data).subscribe(new Action1<Credential>() {

  @Override

  public void call(Credential credential) {

// On a successful credential request, use the resulting Credential object to complete the user's sign-in to your app.

  
}

 
}
);

}
 else {

 Log.e(TAG, "Credential Read: NOT OK");

}

  
}
  
}

For more information, check out the official documentaion on how to handle successful credential requests.

Store a User's Credentials

After users successfully sign in, create accounts, or change passwords, allow them to store their credentials to automate future authentication in your app.

To save users' credentials, you can call the storeCredential(Credential) method on the SmartLock object that you created from anywhere in your Activity. This method returns an observabale Observable<Boolean> which you can subscribe to:

mSubscription = mSmartLock.storeCredential(credential).subscribe(new Subscriber<Boolean>() {

@Override
  public void onCompleted() {

}

@Override
  public void onError(Throwable e) {

  // Try to resolve the save request. 

// This will prompt the user if the credential is new.

if (e instanceof StatusException) {

 Status status = ((StatusException) e).getStatus();

 if (status.hasResolution()) {

  try {

status.startResolutionForResult(MainActivity.this, CREDENTIAL_STORE_RC);

  
}
 catch (IntentSender.SendIntentException e1) {

Log.e(TAG, "STATUS: Failed to send resolution.");

  
}

 
}

}

  
}

@Override
  public void onNext(Boolean aBoolean) {

  if (aBoolean) {

 // We have successfully saved the user's credential.

}

  
}

  
}
);

If the call to SmartLock.storeCredential(Credential) is not immediately successful, the credentials might be new, in which case the user must confirm the save request. Resolve the save request with startResolutionForResult() to prompt the user for confirmation.

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

if (requestCode == CREDENTIAL_STORE_RC) {

if (resultCode == RESULT_OK) {

 Log.d(TAG, "SAVE: OK");

}
 else {

 Log.e(TAG, "SAVE: Canceled by user.");

}

  
}
  
}

To learn more about how to store a user's credentials, check out the official documentaion.

Delete Stored Credentials

Delete credentials from Smart Lock when either of the following circumstances occur:

  • Signing in with the credentials fails because the account no longer exists or the password is incorrect.
  • The user completes the app's account deletion flow.

To delete credentials, you can call the deleteCredential(Credential) method on the SmartLock object that you created from anywhere in your Activity. This method returns an observabale Observable<Boolean> which you can subscribe to:

mSubscription = mSmartLock.deleteCredential(credential).subscribe(new Subscriber<Boolean>() {

@Override
  public void onCompleted() {

}

@Override
  public void onError(Throwable e) {

  // Handle unsuccessful deletion.

if (e instanceof StatusException) {

 Status status = ((StatusException) e).getStatus();

 Log.e(TAG, status.getStatusMessage());

}

  
}

@Override
  public void onNext(Boolean aBoolean) {

  if (aBoolean) {

 // Credential was deleted successfully.

}

  
}

  
}
);

Google Play Services Connection Failures Handling

Since Smart Lock for Passwords is a Google Play Services API, we need to handle possible connection failures when the connection to Google Play services fails or becomes suspended. This is how you can deal with these situtations gracefully when using RxSmartLock:

@Override public void onError(Throwable e) {

if (e instanceof ConnectionSuspendedException) {

int errorCode = ((ConnectionSuspendedException) e).getCode();

// Handle the connection suspension errors here.
  
}
  
}
@Override public void onError(Throwable e) {

if (e instanceof ConnectionException) {

ConnectionResult result = ((ConnectionException) e).getConnectionResult();

// Handle the connection failed errors here.

if (result.hasResolution()) {

 result.startResolutionForResult(MainActivity.this, RESULT_RC);

}

  
}
  
}

You can find more information on how to handle connection failures here.

Add RxSmartLock To Your Project

Add this to your build.gradle file:

dependencies {

compile 'com.shlmlkzdh:rx-smart-lock:1.1.4' 
}

Additional Notes

This library is inspired by the ReactiveLocation library for Android developed by Micha? Charmas and a great blog post written by Sebastiano Poggi on Smart Lock. Thank you guys!

License

Copyright 2015 - 2016 Soheil Malekzadeh  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. 

Resources

Android Json Wizard is a library for creating beautiful form based wizards within your app just by defining json in a particular format.

Android Ticker Text for real.

Custom ImageView for moving image around the screen.

Custom ImageView for android with polygon shape.

There are 3 basic effects:

  • RegularPolygonShape
  • PaperPolygonShape
  • StarPolygonShape

Custom layout that arranges views in rows and columns automatically. Takes care about padding, margins, gravity and layout child gravities.

Super fast and easy way to create header for Android RecyclerView.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes