B4A Library Wearable DataLayer

What is it?
Not so recently a new branch of the Android platform was released for wearables (Watches and things) know simply as Android Wear. Wearables running Android Wear are made to be an extension for your existing mobile Android device. They bring notifications and app information / interaction out of your pocket and onto your wrist (and maybe other places if other wearable devices are released). I believe notifications will account for about 80% of the usage of these wearable devices. Wearable notification support has been possible for a while with the Notification Builder library, and the possibility to make apps that run on Android Wear has also been possible Tutorial. There was still a little issue; your mobile device and your wearable device couldn't talk to each other.

So, here is the Wearable DataLayer library. It allows you to communicate between the 2 devices. There are a couple of ways this works. There are:
  • Messages - these are 'send and forget' one way messages for small amounts of information (<100 KB)
  • DataMaps (Google call them DataItems, externally, but DataMaps internally o_O) - These are maps of data that are kept in sync on the Wear Network (a virtual connection between the devices). This data can be changed from either side and the data will sync to all other devices. DataMaps can hold Strings, Ints, Booleans, etc.
  • Assets - These are technically part of DataMaps but it is easier to explain them separately and you create them like so. Assets are basically used to transfer larger (anything > 100 KB) blocks of information as a File or Bitmaps. Assets are added to DataMaps and the system takes care of the transfer over bluetooth and caching, avoiding re-transmission.
This library has literally taken me an lifetime to make and I can only apologize for that, I hoped it would have been waaaaaay before now but sometimes life gets in the way of hobbies.

How To Install

First of all, copy the .jar and .xml to your additional libraries folder like any other library.

The use of this library requires the inclusion of Google Play Services. Similar to the Android-Support libraries, you have to download this with sdk manager and copy the library file(s) over to your additional libraries folder. A typical place for this would be

C:\Program Files\Android\sdk\extras\google\google_play_services\libproject\google-play-services_lib\libs

Although this path may be different depending on your installation.

It also requires 'AdditionalRes'. Again the path may vary. This is just for the Version ID of Play Services.
#AdditionalRes: C:\Program Files\Android\sdk\extras\google\google_play_services\libproject\google-play-services_lib\res, com.google.android.gms

I will update that post a little in the future and also create / post a few simple examples to help you all out.

Note: I have edited a few bits since my last BIG testing session, hopefully it won't have broken anything. I've run a few tests but thought it was about time I got this online so I will fix any issues as they come up. Also, a lot has changed since the BETA so the examples for that won't work, though the principles are the same so you should be able to get the idea from it.

Documentation

WearableDataLayer
Author:
BarxDroid
Version: 1

  • Methods:
    • AddDynamicListener
      Adds a dynamic listener to receive message events.
      A dynamic listener is create at runtime and will be removed once the process is stopped or once RemoveListener is called.
    • Info
      NOTE: This method doesn't do anything and is to provide information only.
      A Message is used to 'Send and forget' small amounts (<100KB) of data.
      You can receive the messages either with dynamic or static receivers.
      Dynamic - Will only be received while the listener is registered.
      Register with .AddDynamicReceiver.
      You must also unregister once done using .RemoveDynamicReceiver
      static - More complex but means you can receive messages at any time
      Add the following text to the Manifest Editor
      <code>AddApplicationText(
      <service android:name="barxdroid.wearabledatalayer.ListenerService"
      android:label="Wearable Listener">
      <intent-filter>
      <action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
      </intent-filter>
      </service>)
      </code>
      Then add a service called 'WearListenerService to your project and in the service module, use code like this.
      <code>
      Sub Process_Globals
      Dim WL As WearableListener
      End Sub
      Sub Service_Start (StartingIntent As Intent)
      WL.Initialize("WL")
      WL.HandleIntent(StartingIntent)
      End Sub
      Sub WL_MessageReceived(SourceNodeID As String, RequestID As Int, msgPath As String, Data As String)
      ToastMessageShow(Data, False)
      End Sub
      </code>
    • IsInitialized As Boolean
    • RemoveListener
      Removes the dynamic listener so no more messages will be received
    • Send (NodeID As String, Timeout As Long, msgPath As String, Data As String)
      Sends a message to a specified node
      NodeID - The ID of the node to connect to.
      Timeout - The timeout before the message sending will fail in milliseconds.
      Path - Denotes a path identifier to specify a particular endpoint at the receiving node.
      Data - A ByteArray of data to pass. Do not pass >100KB. Pass Null if not required.
  • WearableAsset
    Methods:
    • CreateFromBitmap (bitmap As Bitmap) As Asset
      Creates an Asset to use from a Bitmap
    • CreateFromFile (Dir As String, Filename As String) As Asset
      Creates an Asset to use from a File
    • Info
      This method doesn't do anything, it is here purely for informational purposes.
      An asset is used to send a binary blob of data such as an image.
      You attach an asset to a DataItem.
      The system takes care of conserving bluetooth by caching large assets to avoid re-transmission.
  • WearableDataLayer
    Events:
    • BitmapResult (Tag As String, Result As Bitmap)
    • Connected ( As )
    • ConnectionFailed (ErrorCode As Int, Reason As String)
    • ConnectionSuspended (Reason As String)
    • DataChanged (ChangedItems As Map, DeletedItems As Map)
    • DataMapAdded (Success As Boolean)
    • DataMapDeleted (Path as string As , Success As Boolean)
    • DataMapResults (Success As Boolean, Results As Map)
    • FileResult (Tag As String, Dir As String, Filename As String, Success As Boolean)
    • LocalNodeIDResult (Success As Boolean, NodeID As String, NodeDisplayName As String)
    • MessageReceived (SourceNodeID As String, RequestID As Int, msgPath As String, Data As String)
    • MessageSent (Success As Boolean)
    • NodeResults (Results As List)
    • PeerConnected (ID As Int, DisplayName As String)
    Fields:
    • message As Message
    Methods:
    • AddDataMap (Path As String, dataMap As DataMap)
      Adds a Data Map to the Client to sync across the Wearable Data connection.
      DataMaps are synchronized across all devices
      Path - The path to store the DataMap under. e.g "/User"
      DataMap - The DataMap object to add
      Will call DatamapAdded() once complete returning the path for Identification and the success
      Also triggers DataChanged() event if new information is added
    • ClearCallingIdentity
    • Connect
      Connects the Google Play services client (required for the Data Layer to work)
      The _onConnected event will raise once the connection is successful.
      Do NOT attempt to use the Data Layer until the connection is successful
      Make sure you disconnect the client once done (probably best to do this in Activity_Pause()
    • DeleteDataMap (Path As String)
      Deletes a DataMap
      Path - The path which the DataMap resides.
      Calls DataMapDeleted() Event if present, with the success of the action
    • Disconnect
      Disconnects the Google Play services client
      Should always be called once you have finished with the Data Layer e.g. when the app closes or is paused.
    • GetAllDataMaps
      Returns all the present DataMaps as a Map.
      Each Map Key-Value pair is as follows
      Key - The path that the DataMap resides
      Value - The DataMap object

      The results will be returned in the DataLayer_DataMapResults() event
    • GetBitmapFromAsset (tag As String, asset As Asset)
      Gets a Bitmap from an Asset
      Tag - a Tag used to identify the request in the resulting callback
      Asset - the Asset object to extract the File from
      Result returned in BitmapResult() callback
    • GetConnectedNodes
      Get a list of the connected Nodes (Devices)
      The returned List will contains a Map for each node.
      The map will then contains 3 Key-Value pairs:
      ID - The ID of the node, this is used to reference the node when sending messages etc
      DisplayName - A HumanReadable name for the device (on my Samsung Gear Live this matched the ID so was of no use)
      ToString - A string representation of the full Node object, used mainly for my testing

      Result returned in NodeResults() Event
    • GetDataMap (Path As String, Tag As String)
      Gets an existing DataMap
      Path - the path that the DataMap resides
      Tag - a tag that is passed through to the results to make the result set identifiable
      If there is more than one DataMap with the same Path present on the Wear network. e.g. from different Nodes.
      All the DataMaps with that name will be returned.
      Use GetDataMap2 to specify a Node to narrow down a specific DataMap.
      Results are returned in DatamapResults() Event
    • GetDataMap2 (NodeID As String, Path As String, Tag As String)
      Similar to GetDataMap but allows you to specify a NodeID.
    • GetFileFromAsset (tag As String, asset As Asset, TargetDir As String, TargetFilename As String)
      Gets a File from an Asset
      Tag - A tag used to identify the request in the resulting callback
      Asset - The Asset object to extract the File from.
      TargetDir - The directory where the File will be created
      TargetFilename - The filename that the extracted File will be named
      Result returned in FileResult() callback
    • Initialize (Eventname As String)
      Initializes the object.
      Note: this library requires Android 4.3 (API18) or above
    • LocalNodeID
      Gets the NodeID of the local Device
      Result returned in LocalNodeIDResult() event
    • RestoreCallingIdentity
  • WearableDataMap
    Methods:
    • Clear
      Clears all previously added data items from the DataMap
    • ContainsKey (Key As String) As Boolean
      Checks if the given key is contained in the DataMap.
      Returns True if the key is present
    • Get (Key As String) As Object
      Returns the DataMap entry with the given Key as an Object
    • GetAsset (Key As String) As Asset
      Gets an Asset data item from the DataMap
      Key - The reference as set in in the PutAsset() method
    • GetBoolean (Key As String) As Boolean
      Gets a Boolean data item from the DataMap
      Key - The reference as set in in the PutBoolean() method
    • GetByte (Key As String) As Byte
      Gets a Byte data item from the DataMap
      Key - The reference as set in in the PutByte() method
    • GetByteArray (Key As String) As Byte[]
      Gets a Byte Array data item from the DataMap
      Key - The reference as set in in the PutByteArray() method
    • GetDouble (Key As String) As Double
      Gets a Double data item from the DataMap
      Key - The reference as set in in the PutDouble() method
    • GetFloat (Key As String) As Float
      Gets a Float data item from the DataMap
      Key - The reference as set in in the PutFloat() method
    • GetFloatArray (Key As String) As Float[]
      Gets a Float Array data item from the DataMap
      Key - The reference as set in in the PutFloatArray() method
    • GetInt (Key As String) As Int
      Gets an Int data item from the DataMap
      Key - The reference as set in in the PutInt() method
    • GetLong (Key As String) As Long
      Gets a Long data item from the DataMap
      Key - The reference as set in in the PutLong() method
    • GetLongArray (Key As String) As Long[]
      Gets a Long Array data item from the DataMap
      Key - The reference as set in in the PutLongArray() method
    • GetString (Key As String) As String
      Gets a String data item from the DataMap
      Key - The reference as set in in the PutString() method
    • GetStringArray (Key As String) As String[]
      Gets a StringArray data item from the DataMap
      Key - The reference as set in in the PutStringArray method
    • Initialize
      Initializes the object.
      No Eventname is required. The DataLayer Eventname is used.
    • IsInitialized As Boolean
    • PutAsset (Key As String, Asset As Asset)
      Adds an Asset data item to the DataMap
      Key - a key used to reference the data item
      Asset - the Asset object to pass.
    • PutBoolean (Key As String, Val As Boolean)
      Adds a Boolean data item to the DataMap
      Key - a key used to reference the data item
      Val - the value to set to.
    • PutByte (Key As String, Val As Byte)
      Adds a Byte data item to the DataMap
      Key - a key used to reference the data item
      Val - the value to set to.
    • PutByteArray (Key As String, Val() As Byte)
      Adds a Byte Array data item to the DataMap
      Key - a key used to reference the data item
      Val - the value to set to.
    • PutDouble (Key As String, Val As Double)
      Adds a Double data item to the DataMap
      Key - a key used to reference the data item
      Val - the value to set to.
    • PutFloat (Key As String, Val As Float)
      Adds a Float data item to the DataMap
      Key - a key used to reference the data item
      Val - the value to set to.
    • PutFloatArray (Key As String, Val() As Float)
      Adds a Float Array data item to the DataMap
      Key - a key used to reference the data item
      Val - the value to set to.
    • PutInt (Key As String, Val As Int)
      Adds an Int data item to the DataMap.
      Key - a key use to reference the data item
      Val - the value to set to.
    • PutLong (Key As String, Val As Long)
      Adds a Long data item to the DataMap
      Key - a key used to reference the data item
      Val - the value to set to.
    • PutLongArray (Key As String, Val() As Long)
      Adds a Long Array data item to the DataMap
      Key - a key used to reference the data item
      Val - the value to set to.
    • PutString (Key As String, Val As String)
      Adds a String data item to the DataMap
      Key - a key used to reference the data item
      Val - the value to set to.
    • PutStringArray (Key As String, Val() As String)
      Adds a String Array data item to the DataMap
      Key - a key used to reference the data item
      Val - the value to set to.
    • Remove (Key As String)
      Removes an item from the DataMap with the given Key
    • Size As Int
      Returns the number of Key-Value pairs currently in the DataMap
    • isEmpty As Boolean
      Return True if the DataMap is currently empty
    • toByteArray As Byte[]
      Returns the DataMap as a ByteArray
    • toString As String
      Returns a string representation of the DataMap
  • WearableListener
    Events:
    • DataChanged (ChangedItems As Map, DeletedItems As Map)
    • MessageReceived (SourceNodeID As String, RequestID As Int, msgPath As String, Data As String)
    Methods:
    • HandleIntent (StartingIntent As IntentWrapper) As Boolean
      Used to handle the starting intent when using static listeners.
      Will call the following events:
      _MessageReceived - When a message is received
      _DataChanged - When a DataMap is changed on the Wear Network
    • Initialize (EventName As String)
      initilizes the object and set the EventName for callback events

To Be Continued.............
 

Attachments

  • WearableDataLayer.zip
    30.8 KB · Views: 612

Ph1lJ

Member
Licensed User
Longtime User
What about a log from the watch?
I've tried to get that but there is nothing shown, probably doing it wrong - can anyone enlighten me (I thought you just set that to debug - like I said no doubt wrong)
 

barx

Well-Known Member
Licensed User
Longtime User
I've tried to get that but there is nothing shown, probably doing it wrong - can anyone enlighten me (I thought you just set that to debug - like I said no doubt wrong)
Yes you get Developer options same as mobile and enable USB Debugging. The tricky bit is the driver. Check device manager and see if the driver is installed properly. if it is then just plug usb cable in and go about it as normal.

If not, I put a post somewhere on it. think it was this thread tbh.
 

barx

Well-Known Member
Licensed User
Longtime User
So the watch and Client are connected then, hence the node ID.

I will update my watch and see if I suffer the same...

I updated my watch and everything still works correct. Have you tried the Dynamic Example? On that one you have to start the app on phone first and send the message which watch is still alive
 

Ph1lJ

Member
Licensed User
Longtime User
Well I think I got the driver sorted, but fail to see how to connect B4a to use the debug via USB To the watch. Sorry about this, feeling a bit stupid at the moment. I haven't tried the 2nd example yet - was hoping to sort this one first.
 

barx

Well-Known Member
Licensed User
Longtime User
Well I think I got the driver sorted, but fail to see how to connect B4a to use the debug via USB To the watch. Sorry about this, feeling a bit stupid at the moment. I haven't tried the 2nd example yet - was hoping to sort this one first.
Never seen the LG G Watch but on my Gear Live I just connect the charging cradle and pllug the usb in. How do you charge the G Watch?
 

Ph1lJ

Member
Licensed User
Longtime User
Yeah got that bit, what do I do to B4A to get the debug data from the USB, I use the B4A Bridge through wireless hundreds of times, not via the USB cable.
 

barx

Well-Known Member
Licensed User
Longtime User
Yeah got that bit, what do I do to B4A to get the debug data from the USB, I use the B4A Bridge through wireless hundreds of times, not via the USB cable.

just go to the 'Log' tab and click connect
 

Ph1lJ

Member
Licensed User
Longtime User
OK - did that, see attached for what is being reported
I don't think the connection between the Tablet & Watch has been established.

One thing I have noticed is that Starting the watch app causes the Tablet app to seemly refresh, screen goes blank and then restore - doesn't do that normally

Anyone got any ideas
 

Attachments

  • From Gear Live via USB.png
    From Gear Live via USB.png
    32.5 KB · Views: 221
Last edited:

Ph1lJ

Member
Licensed User
Longtime User
I just tried out the Dynamic version Example #2, on the Samsung Live - see the results of the watch USB LOG attached, - when I start the watch app, the screen changes colour and says its listening, it remains on that screen regardless of what I send from the tablet.
 

Attachments

  • Log from Dynamic version.png
    Log from Dynamic version.png
    31.6 KB · Views: 208

Rick in North Carolina

Member
Licensed User
Longtime User
Hi Barx,
Im running your dynamic example and get "Failed2" for Google Play Services on Wearable (LG G Watch).
Can you shed any lighton this error?
Thanks, Rick

Log:
** Activity (main) Create, isFirst = true **

** Activity (main) Resume **
Google Play Services Client Connection Failed
Failed2
 

barx

Well-Known Member
Licensed User
Longtime User
Hi Barx,
Im running your dynamic example and get "Failed2" for Google Play Services on Wearable (LG G Watch).
Can you shed any lighton this error?
Thanks, Rick

Log:
** Activity (main) Create, isFirst = true **

** Activity (main) Resume **
Google Play Services Client Connection Failed
Failed2

Hi Rick, there is a built in sub you can add to get better info.

B4X:
ConnectionFailed(ErrorCode As Int, Reason As String)

In your case above the reason is:

"The installed version of Google Play Services is out of date"
 

Rick in North Carolina

Member
Licensed User
Longtime User
Thanks Barx, that helped.
I just needed to Resync apps (phone -> Wear application ->settings) to have the Google Play Services version be the same for phone and watch. It took about 5 min to Resync.

** Now that it starts (Dynamic sample for phone and watch) , I think I am having the same problem as Ph1lj above, that nothing is received on the watch (LG G watch).. log files below. I am going to try the static sample next and see if that works.

** Yes the Static sample works.... just not the Dynamic.
Rick
 

Attachments

  • Phone_Dynamic_Log.txt
    467 bytes · Views: 238
  • Wearable_Dynamic_Log.txt
    432 bytes · Views: 218
Last edited:

Ph1lJ

Member
Licensed User
Longtime User
Thanks Barx, that helped.
I just needed to Resync apps (phone -> Wear application ->settings) to have the Google Play Services version be the same for phone and watch. It took about 5 min to Resync.

** Now that it starts (Dynamic sample for phone and watch) , I think I am having the same problem as Ph1lj above, that nothing is received on the watch (LG G watch).. log files below. I am going to try the static sample next and see if that works.

** Yes the Static sample works.... just not the Dynamic.
Rick
Hi Rick
Can you tell me which software version your watch is using, I still cant get mine to do anything

cheers
 

Rick in North Carolina

Member
Licensed User
Longtime User
Hi Ph1lj,

Software version - 5.0.2

Click "Software Version"
Android Wear - 1.0.5.1724356
Google Play Services - 7.0.95 (1784785-534)

Good Luck,
Rick
 

Ph1lJ

Member
Licensed User
Longtime User
thanks, unfortunately mine is exactly the same but still refuses to work.

Shame as I was going to use this in a class-room activity.

Guess there are still issues with Android Wear

Thanks
 

barx

Well-Known Member
Licensed User
Longtime User
thanks, unfortunately mine is exactly the same but still refuses to work.

Shame as I was going to use this in a class-room activity.

Guess there are still issues with Android Wear

Thanks


I'm going to uninstall all my demo apps, download the example from this thread anf try it out... Mybe there is something I'm missing
 

barx

Well-Known Member
Licensed User
Longtime User
OK, I think I know what is going on.....

The already packaged wearable_app.apk is compiled by me with my license key. So, if you just run the 'mobile' project, compile it and install it; both parts install (mobile and wearable) but the mobile part will be signed with your key, NOT mine.

So, what do you do to sort it.

Short answer, re-compile and insert the wearable app.

Long answer:
  • Load the Wearable project in B4A (found in the /wearable folder
  • Change the path for the additional resources if it doesn't match your system
  • Compile the project with no devices connected to your pc, B4A will complain that there are no devices but it still compiles the project
  • Find the wearable_app.apk in the /wearable/Objects directory
  • Copy that .apk to mobile/Object/res/raw and make it read only
  • Load the mobile project (found in /mobile) (you can close the wearable one if you like as we are done with it now)
  • Change the path for the additional resources if it doesn't match your system
  • Compile the mobile project and install it to your mobile device as you normally would.
All should hopefully be correct in the world again

please let me know how it goes
 

Ph1lJ

Member
Licensed User
Longtime User
OK, I think I know what is going on.....

The already packaged wearable_app.apk is compiled by me with my license key. So, if you just run the 'mobile' project, compile it and install it; both parts install (mobile and wearable) but the mobile part will be signed with your key, NOT mine.

So, what do you do to sort it.

Short answer, re-compile and insert the wearable app.

Long answer:
  • Load the Wearable project in B4A (found in the /wearable folder
  • Change the path for the additional resources if it doesn't match your system
  • Compile the project with no devices connected to your pc, B4A will complain that there are no devices but it still compiles the project
  • Find the wearable_app.apk in the /wearable/Objects directory
  • Copy that .apk to mobile/Object/res/raw and make it read only
  • Load the mobile project (found in /mobile) (you can close the wearable one if you like as we are done with it now)
  • Change the path for the additional resources if it doesn't match your system
  • Compile the mobile project and install it to your mobile device as you normally would.
All should hopefully be correct in the world again

please let me know how it goes
Some good news, the Static version now works, however the same process does not yield anything with the Dynamic version - indeed it wont even install on the watch, no errors during compilation, just nothing on watch. However if I leave this in the manifest it does seem to install

<meta-data android:name="com.google.android.wearable.beta.app"
android:resource="@xml/wearable_app_desc"/>

but get an error msg on the watch, basically the same as I got in #31, however the fix for that error, worked for the Static version worked, but not for the Dynamic.
 

barx

Well-Known Member
Licensed User
Longtime User
Some good news, the Static version now works, however the same process does not yield anything with the Dynamic version - indeed it wont even install on the watch, no errors during compilation, just nothing on watch. However if I leave this in the manifest it does seem to install

<meta-data android:name="com.google.android.wearable.beta.app"
android:resource="@xml/wearable_app_desc"/>

but get an error msg on the watch, basically the same as I got in #31, however the fix for that error, worked for the Static version worked, but not for the Dynamic.

You need the meta tag in the manifest.....

Th error in #31 relates to the version of google play services you are referencing. see #33

basically you have 1 version in your additional libs folder but another (probably newer) version in your android/SDK/.... folder.
 

Ph1lJ

Member
Licensed User
Longtime User
Hi Barx
That's what I thought - so did just what you suggested again, but I still get this error during compiling of the Dynamic example (no mod's - just your code), I have also attached the manifest from the mobile app. The wearable app compiles no problem. Sorry to be a pain - I really appreciate your efforts

Ph1lj
 

Attachments

  • Compiling.jpg
    Compiling.jpg
    72.1 KB · Views: 205
  • Tablet manifest.jpg
    Tablet manifest.jpg
    125.6 KB · Views: 190
Top