RxGcm


Source link: https://github.com/VictorAlbertos/RxGcm

[DEPRECATED] Use RxFcm instead. Their APIs are almost identical so there should not be any problem to migrate from RxGcm to RxFcm.

RxGcm

RxJava extension for Gcm which acts as an architectural approach to easily satisfy the requirements of an android app when dealing with push notifications.

Features:

  • Remove android boilerplate code (not need for Manifest or Service(s) configuration).
  • Decouple presentation responsibilities from data responsibilities when receiving notifications.
  • Deploy a targeting strategy to aim for the desired Activity/Fragment when receiving notifications.

Setup

Add RxGcm dependency and Google Services plugin to project level build.gradle.

apply plugin: 'com.google.gms.google-services'  dependencies {

  compile 'com.github.VictorAlbertos:RxGcm:0.3.0'
  compile 'io.reactivex:rxjava:1.1.5' 
}

Add Google Services to classpath and jitpack repository to root level build.gradle.

dependencies {

classpath 'com.google.gms:google-services:2.1.0' 
}
  allprojects {

  repositories {

//..

maven {
 url "https://jitpack.io" 
}

  
}
 
}
 

There is, thought, one step behind which RxGcm can't do for you. You need to create a google-services.json configuration file and place it in your Android application module. (You can create and download it from here)

Usage

GcmReceiverData

GcmReceiverData implementation should be responsible for updating the data models. The onNotification method requires to return an instance of the observable supplied as argument, after applying doOnNext operator to perform the update action:

public class AppGcmReceiverData implements GcmReceiverData {
??

 @Override public Observable<Message> onNotification(Observable<Message> oMessage) {
?

return oMessage.doOnNext(message -> {

}
);
?

 
}
?
  
}

The observable type is an instance of Message, which holds a reference to the android Application instance, the Bundle notification and a method called target(), which returns the key associated with this notification.

public class AppGcmReceiverData implements GcmReceiverData {

@Override public Observable<Message> onNotification(Observable<Message> oMessage) {

return oMessage.doOnNext(message -> {

 Bundle payload = message.payload();

  String title = payload.getString("title");

 String body = payload.getString("body");

  if (message.target().equals("issues")) SimpleCache.addIssue(new Notification(title, body));

 else if (message.target().equals("supplies")) SimpleCache.addSupply(new Notification(title, body));

}
);

  
}

}
 

To RxGcm be able to return a not null string value when calling target() method, you need to add the key rx_gcm_key_target to the payload of the push notification:

{

 "data": {

  "title":"A title 4",
  "body":"A body 4",
  "rx_gcm_key_target":"supplies"

}
,
"to":"token_device"

}
 
}

If rx_gcm_key_target is not added to the json payload, you will get a null value when calling the target() method. So, you can ignore this, but you would be missing the benefits of the targeting strategy.

GcmReceiverUIBackground and GcmReceiverUIForeground

Both of them will be called only after GcmReceiverData observable has reached onCompleted() state. This way it’s safe to assume that any operation related to updating the data model has been successfully achieved, and now it’s time to reflect these updates in the presentation layer.

GcmReceiverUIBackground

GcmReceiverUIBackground implementation will be called when a notification is received and the application is in the background. Probably the implementation class will be responsable for building and showing system notifications.

public class AppGcmReceiverUIBackground implements GcmReceiverUIBackground {
??

 @Override public void onNotification(Observable<Message> oMessage) {
?

  oMessage.subscribe(message -> buildAndShowNotification(message));
?

}

}

GcmReceiverUIForeground

GcmReceiverUIForeground implementation will be called when a notification is received and the application is in the foreground. The implementation class must be an Activity or an android.support.v4.app.Fragment. GcmReceiverUIForeground exposes a method called matchesTarget(), which receives an string (the value of the rx_gcm_key_target node payload notification) and forces to the implementation class to return a boolean.

If the current Activity or visible Fragment matchesTarget() method returns true, onTargetNotification() method will be called, otherwise onMismatchTargetNotification() method will be called.

public abstract class BaseFragment extends android.support.v4.app.Fragment implements GcmReceiverUIForeground {
??

  @Override public void onMismatchTargetNotification(Observable<Message> oMessage) {

oMessage.subscribe(message -> {

 showAlert(message);

}
);

  
}

  ? 
}
public class FragmentIssues extends BaseFragment {
??

  @Override public void onTargetNotification(Observable<Message> oMessage) {

oMessage.subscribe(message -> {

 notificationAdapter.notifyDataSetChanged();

}
);

  
}

  @Override public boolean matchesTarget(String key) {

return "issues".equals(key);

  
}

? 
}
public class FragmentSupplies extends android.support.v4.app.Fragment implements GcmReceiverUIForeground {
??

  @Override public void onTargetNotification(Observable<Message> oMessage) {

oMessage.subscribe(message -> {

 notificationAdapter.notifyDataSetChanged();

}
);

  
}

  ?  @Override public boolean matchesTarget(String key) {

return "supplies".equals(key);

  
}
 
}

Limitation:: Your fragments need to extend from android.support.v4.app.Fragment instead of android.app.Fragment, otherwise they won't be notified.

RefreshTokenReceiver

GcmRefreshTokenReceiver implementation will be called when the token has been updated. As the documentation points out, the token device may need to be refreshed for some particular reason.

public class RefreshTokenReceiver implements GcmRefreshTokenReceiver {

 @Override public void onTokenReceive(Observable<TokenUpdate> oTokenUpdate) {

oTokenUpdate.subscribe(tokenUpdate -> {

}
, error -> {

}
);

  
}

}

Retrieving current token

If at some point you need to retrieve the gcm token device -e.g for updating the value on your server, you could do it easily calling RxGcm.Notifications.currentToken:

 RxGcm.Notifications.currentToken().subscribe(token -> {

}
, error -> {

}
);

Register RxGcm classes

Once you have implemented GcmReceiverData and GcmReceiverUIBackground interfaces is time to register them in your Android Application class calling RxGcm.Notifications.register. Plus, register RefreshTokenReceiver implementation too at this point.

public class RxSampleApp extends Application {

@Override public void onCreate() {

super.onCreate();

 RxGcm.Notifications.register(this, AppGcmReceiverData.class, AppGcmReceiverUIBackground.class)

  .subscribe(token -> {

}
, error -> {

}
);

  RxGcm.Notifications.onRefreshToken(RefreshTokenReceiver.class);

  
}
  
}

Important: The observable returned by RxGcm.Notifications.register()method will not emit the token twice. It means that it will be emit the token only the first time RxGgm asks to Google for a token. But if the token is already cached, the observable will complete without emitting the item.

Threading

RxGcm.Notifications.register method uses internally RxAndroid. Thanks to this, the observable provided observes on the Main Thread and subscribes on an IO thread. This means you do not need to worry about threading and sync. But if you need to change this behaviour, you can do it easily setting in which scheduler the observable needs to observe and subscribe.

Examples

There is a complete example of RxGcm in the app module. Plus, it has an integration test managed by Espresso test kit which show several uses cases.

Testing notification

You can easily send http post request to Google Cloud Messaging server using Postman or Advanced Rest Client. Or you can send directly push notifications using this page.

Author

Víctor Albertos

Another author's libraries using RxJava:

  • RxCache: Reactive caching library for Android and Java.
  • RxPaparazzo: RxJava extension for Android to take images using camera and gallery.
  • RxActivityResult: A reactive-tiny-badass-vindictive library to break with the OnActivityResult implementation as it breaks the observables chain.

Resources

A log library focused on high extensibility.

A group of toggle buttons, supports multiple / single selection.

This is an encryption example of RSA and AES (CBC, ECB, CTR) 256 bit key on android with unit tests.

AndroidStudio/IntelliJ IDEA code style settings for Android projects.

A nearby handling APIs for Android Apps using RxJava.

An android app to track bus status of Zhuhai using RxJava and Android Data Binding library.

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