Courier


Source link: https://github.com/denley/courier

Courier

A delivery service for Android Wear. Courier uses Wearable.DataApi and Wearable.MessageApi to deliver objects between devices simply and cleanly.

Usage

Build Dependency

Using the jcenter repository, add the following line to the gradle dependencies for your modules. You should add this to both your handheld and wearable modules.

compile 'me.denley.courier:courier:1.2.1'

Basic Usage

Simply add @ReceiveMessages and @ReceiveData annotations to your methods and fields to assign them as callbacks for MessageApi and DataApi events. Call Courier.startReceiving(this) to initialize the listeners and start receiving your callbacks.

public class MainActivity extends Activity  {

@ReceiveData("/username")
  String loggedInUser;

@Override protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

 Courier.startReceiving(this);

  
}

@Override protected void onDestroy() {

super.onDestroy();

Courier.stopReceiving(this);

  
}

@ReceiveMessages("/incoming_sms")
  void onSmsReceived(SmsDescriptor smsMessage, String nodeId) {
 // The nodeId parameter is optional

// ...
  
}
  
}

On the other device, use `Courier.deliverMessage` and `Courier.deliverData` to easily send data using the `MessageApi` and `DataApi`, respectively
public void onLoginSuccess(String username) {

  Courier.deliverData(this, "/username", username);
 
}

Checking for Connected Devices

Wearable API Status

Often it will be prudent to check whether or not the user has a wearable device paired with their phone. For this, you can use the following method:

// This must be done on a background thread boolean hasWearableDevice = Courier.isWearableApiAvailable(context);

Note: This is not the same as whether or not the watch is in range of the phone ("connected"). It determines whether the user has the Android Wear app installed and has paired a wearable device.

If this method returns false, all other method calls to the Courier class will simply be ignored, and return null where applicable.

Connected Devices

You can retrieve a list of connected devices using the @RemoteNodes annotation. When devices are connected or disconnected, the callback will be invoked again. This represents devices that are paired, in range, and ready to send and receive data and messages.

@RemoteNodes void onConnectionStateChanged(List<Node> connectedNodes) {

  // Do something with the nodes
  // ... 
}

Local Device

Sometimes having the local node can be useful. For example, you might want to ignore data items originating from the same device.

You can retrieve the local node using the @LocalNode annotation. This will only be updated once, as it never changes. Alternatively, you can retrieve the local node by calling Courier.getLocalNode(context). This must be done on a background thread.

@LocalNode Node localNode;

Or:

// This must be done on a background thread localNode = Courier.getLocalNode(context);

Threading

By default, method calls will be made on the main thread. If you want a callback to be made on a background thread, you can use the @BackgroundThread annotation on a method, like so:

@BackgroundThread @ReceiveMessages("/incoming_sms") void onSmsReceived(SmsDescriptor smsMessage) {

  // ... 
}

Object Serialization

To be delivered between devices, objects must be able to be serialized into a byte array. Objects of any class implementing Serializable can be delivered. This includes primatives, Strings, and many other classes in the Android API. For custom classes it is recommended to avoid relying on the Serializable interface, as it will restrict your ability to change your data structures in the future.

Instead, annotate your classes with Courier's @Deliverable annotation. This will automatically generate methods to convert your objects into a DataMap and back again. For example:

@Deliverable public class SmsDescriptor {

String sender;
  String messageText;
  long timestamp;  
}

@Deliverable classes support any field types that can be saved into a DataMap as well as any other @Deliverable or Seriializable object types.

Assets can also be included as fields, and should be used for any large blobs of data (anything larger than a few kilobytes). When received, Assets can be opened using the Courier.getAssetInputStream method. @Deliverable classes can also contain Bitmap fields, which will automatically be transferred as Assets.

WearableListenerService

Often you will want to listen for message and data events outside of your 'Activity' using a WearableListenerService.

Courier is completely compatible with WearableListenerService. In this class your code will look very similar with or without using Courier, but Courier can help you to unpack any messages/data that were sent using Courier.deliverMessage or Courier.deliverData.

Example:

@Override public void onMessageReceived(MessageEvent messageEvent) {

  if (messageEvent.getPath().equals("/incoming_sms")) {

SmsDescriptor mySms = Packager.unpack(this, messageEvent.getData(), SmsDescriptor.class);

 // Do something with the message

// ...
  
}
 
}
  @Override public void onDataChanged(DataEventBuffer dataEvents) {

  for(DataEvent event:dataEvents) {

if (event.getUri().getPath().equals("/username")) {

 String username = Packager.unpack(this, event.getDataItem(), String.class);

  // Do something with the data

 // ...

}

  
}
 
}

The Courier.getLocalNode convenience method can also be useful in a WearableListenerService, as you might want to ignore data events that are sent from the local device.

Miscellaneous

  • @DeliverData callbacks will be invoked immediately after calling Courier.startReceiving (but asynchronously).
  • @DeliverData callbacks will also be called immediately when the device connects to a device.
  • @DeliverMessage callbacks will only be invoked at the time that a message is received from the MessageApi (they are missed if the device is disconnected).
  • If an empty message is sent or if a data item is removed, a null object will be passed to the listener. Be sure to check for null values!

Testing

Courier supports using mock implementations of the wearable API for unit testing. Simply call Courier.attachMockDataApi, Courier.attachMockMessageApi, and Courier.attachMockNodeApi to provide your testing API implementations. Mocked APIs will be called with a null GoogleApiClient object. Your mock APIs should be attached before making any calls to Courier.startReceiving and you should not attach new APIs until all targets have called Courier.stopReceiving.

ProGuard Configuration

If you use ProGuard, you will need to add the following lines to your configuration. You will probably need to add this to the configurations for both your handheld and wearable modules.

-keep class me.denley.courier.** {
 *; 
}
 -dontwarn me.denley.courier.compiler.** -keep class **$$Delivery {
 *; 
}
 -keep class **DataMapPackager {
 *; 
}
 -keepclasseswithmembernames class * {

  @me.denley.courier.* <fields>; 
}
 -keepclasseswithmembernames class * {

  @me.denley.courier.* <methods>; 
}
 -keep @me.denley.courier.* public class * {
 *; 
}
 

License

Copyright 2015 Denley Bihari  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

A simple router lib to android.

Groupie helps you display and manage complex RecyclerView layouts.

@BindingAdapter for loading the images with Glide without writing a single line of code using Data Binding Library.

Avatar ImageView with user's name first letter Drawable placeholder.

An Annotation based validation library for use with Android's DataBinding library in an MVVM architecture.

  • Quick and easily add validation rules to ViewModels by annotating the class.
  • Annotation Processing to eliminate reflection and generate boilerplate validation classes.

IntelliJ Idea, Android Studio plugin for JSON to POJO conversion.

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