您好,欢迎来到筏尚旅游网。
搜索
您的当前位置:首页android wear的相关知识

android wear的相关知识

来源:筏尚旅游网
Sending and Syncing Data Get started Dependencies and prerequisites

Android 4.3 (API Level 18) or higher on the handset device The latest version of Google Play services An Android Wear device or Wear AVD

The Wearable Data Layer API, which is part of Google Play services, provides a communication channel for your handheld and wearable apps. The API consists of a set of data objects that the system can send and synchronize over the wire and listeners that notify your apps of important events with the data layer: Data Items

A DataItem provides data storage with automatic syncing between the handheld and wearable. Messages

The MessageApi class can send messages and is good for remote procedure calls (RPC), such as controlling a handheld's media player from the wearable or starting an intent on the wearable from the handheld. Messages are also great for one-way requests or for a request/response communication model. If the handheld and wearable are connected, the system queues the message for delivery and returns a successful result code. If the devices are not connected, an error is returned. A successful result code does not indicate that the

message was delivered successfully as the devices may disconnect after receiving the result code. Asset

Asset

objects are for sending binary blobs of data, such as images.

You attach assets to data items and the system automatically takes care of the transfer for you, conserving Bluetooth bandwidth by caching large assets to avoid re-transmission. WearableListenerService (for services)

Extending WearableListenerService lets you listen for important data layer events in a service. The system manages the lifecycle of theWearableListenerService, binding to the service when it needs to send data items or messages and unbinding the service when no work is needed. DataListener (for foreground activities)

Implementing DataListener in an activity lets you listen for important data layer events when an activity is in the foreground. Using this instead of the WearableListenerService lets you listen for changes only when the user is actively using your app. Channel

You can use the ChannelApi class to transfer large data items, such as music and movie files, from a handheld to a wearable device. The Channel API for data transfer has the following benefits:

Transfer large data files between two or more connected devices, without the automatic synchronization provided when using Asset objects attached to DataItem objects. The Channel API saves disk space unlike the DataApi class, which creates a copy of the assets on the local device before synchronizing with connected devices.

Reliably send a file that is too large in size to send using the MessageApi class.

Transfer streamed data, such as music pulled from a network server or voice data from the microphone.

Warning: Because these APIs are designed for communication between handhelds and wearables, these are the only APIs you should use to set up communication between these devices. For instance, don't try to open low-level sockets to create a communication channel.

Android Wear supports multiple wearables connected to a handheld device. For example, when the user saves a note on a handheld, it automatically appears on both of the user's Wear devices. To synchronize data between devices, Google’s servers host a cloud node in the network of devices. The system synchronizes data to directly connected devices, the cloud node, and to wearable devices connected to the cloud node via Wi-Fi.

Figure 1. A sample network of nodes with handheld and wearable devices.

Lessons

Accessing the Wearable Data Layer

This lesson shows you how to create a client to access the Data Layer APIs.

Syncing Data Items

Data items are objects that are stored in a replicated data store that is automatically synced from handhelds to wearables. Transferring Assets

Assets are binary blobs of data that you typically use to transfer images or media.

Sending and Receiving Messages

Messages are designed for fire-and-forget messages that you can send back and forth between the wearable and handheld. Handling Data Layer Events

Be notified of changes and events to the data layer.

Accessing the Wearable Data Layer PreviousNext This lesson teaches you to .

Set up a Google Play services client to use the Wearable Data Layer APIs

Dependencies and Prerequisites . .

Creating Wearable Apps > Set Up an Android Wear Emulator or Device Creating Wearable Apps > Creating a Project

To call the Data Layer API, create an instance of GoogleApiClient, the main entry point for any of the Google Play services APIs.

GoogleApiClient provides a builder that makes it easy to create an instance of

the client. A minimalGoogleApiClient looks like this:

Note: For now, this minimal client is enough to get started. However, see Accessing Google Play services APIs for more information about creating a GoogleApiClient, implementing its callbacks, and handling error cases.

GoogleApiClient mGoogleApiClient =newGoogleApiClient.Builder(this) .addConnectionCallbacks(newConnectionCallbacks(){ @Override publicvoid onConnected(Bundle connectionHint){ Log.d(TAG,\"onConnected: \"+ connectionHint); // Now you can use the Data Layer API } @Override publicvoid onConnectionSuspended(int cause){ Log.d(TAG,\"onConnectionSuspended: \"+ cause); } }) .addOnConnectionFailedListener(newOnConnectionFailedListener(){ @Override publicvoid onConnectionFailed(ConnectionResult result){ Log.d(TAG,\"onConnectionFailed: \"+ result); } }) // Request access only to the Wearable API .addApi(Wearable.API) .build(); Important: If you are adding multiple APIs to a GoogleApiClient, you may run into client connection errors on devices that do not have the Android Wear app installed. To avoid connection errors, call the addApiIfAvailable() method and pass in the Wearable API to indicate that your client should gracefully handle the missing API. For more information, see Access the Wearable API. Before you use the data layer API, start a connection on your client by calling the connect() method, as described in Start a Connection. When the system invokes the onConnected() callback for your client, you're ready to use the Data Layer API.

Syncing Data Items PreviousNext This lesson teaches you to . .

Sync Data with a Data Map Listen for Data Item Events

A DataItem defines the data interface that the system uses to synchronize data between handhelds and wearables. A DataItem generally consists of the following items:

 Payload - A byte array, which you can set with whatever data you wish, allowing you to do your own object serialization and deserialization. The size of the payload is limited to 100KB.

 Path - A unique string that must start with a forward slash (for instance, \"/path/to/data\")

You normally don't implement DataItem directly. Instead, you:

1.

Create a PutDataRequest object, specifying a string path to uniquely identify the item.

2. 3.

Call setData() to set the payload.

If a delay in syncing would negatively impact user experience, call setUrgent().

4.

Call DataApi.putDataItem() to request the system to create the data item.

When requesting data items, the system returns objects that properly implement the DataItem interface. However, instead of working with raw bytes using setData(), we recommend you use a data map, which exposes a data item in an easy-to-use Bundle-like interface.

Sync Data with a Data Map

When possible, use the DataMap class. This approach lets you work with data items in the form of an Android Bundle, so the system does object serialization and deserialization for you, and you can manipulate data with key-value pairs. To use a data map:

1. Create a PutDataMapRequest object, setting the path of the data item.

Note: The path string is a unique identifier for the data item that allows you to access it from either side of the connection. The path must begin with a forward slash. If you're using hierarchical data in your app, you should create a path scheme that matches the structure of the data.

2. 3.

Call PutDataMapRequest.getDataMap() to obtain a data map that you can set values on.

4.

Set any desired values for the data map using the put...() methods, such as putString().

5.

If a delay in syncing would negatively impact user experience, call setUrgent().

6.

Call PutDataMapRequest.asPutDataRequest() to a PutDataRequest object.

obtain

7. Call DataApi.putDataItem() to request the system to create the data item.

Note: If the handset and wearable devices are disconnected, the data is buffered and synced when the connection is re-established.

8.

The increaseCounter() method in the following example shows how to create a data map and put data in it:

publicclassMainActivityextendsActivityimplements DataApi.DataListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{ privatestaticfinalString COUNT_KEY =\"com.example.key.count\"; privateGoogleApiClient mGoogleApiClient; privateint count =0; ... // Create a data map and put data in it privatevoidincreaseCounter(){ PutDataMapRequest putDataMapReq =PutDataMapRequest.create(\"/count\"); putDataMapReq.getDataMap().putInt(COUNT_KEY, count++); PutDataRequest putDataReq = putDataMapReq.asPutDataRequest(); PendingResult pendingResult = Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq); } ... } For more information about handling the PendingResult object, see Wait for the Status of Data Layer Calls.

Set DataItem priority

In Google Play services 8.3 and later, the DataApi interface allows urgent requests for syncing of DataItems. Normally, the system may delay delivery ofDataItems to the Wear network in order to improve battery life for user devices, but if a delay in syncing DataItems would negatively impact user experience, you can mark them as urgent. For example, in a remote control app where the user expects their actions to be reflected immediately, you can have the system sync your DataItems immediately by calling setUrgent(). If you do not call setUrgent(), the system may delay up to 30 minutes before syncing non-urgent DataItems, but you can usually expect the delay to be a few minutes, if at all. The default urgency is now non-urgent, so you must use setUrgent() if you wish to retain the immediate-sync behavior that existed in previous versions of the Wear API.

Listen for Data Item Events

If one side of the data layer connection changes a data item, you probably want to be notified of any changes on the other side of the connection. You can do this by implementing a listener for data item events.

The code snippet in the following example notifies your app when the value of the counter defined in the previous example changes:

publicclassMainActivityextendsActivityimplements DataApi.DataListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{ privatestaticfinalString COUNT_KEY =\"com.example.key.count\"; privateGoogleApiClient mGoogleApiClient; privateint count =0; @Override protectedvoid onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGoogleApiClient =newGoogleApiClient.Builder(this) .addApi(Wearable.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); } @Override protectedvoid onResume(){ super.onResume(); mGoogleApiClient.connect(); } @Override publicvoid onConnected(Bundle bundle){ Wearable.DataApi.addListener(mGoogleApiClient,this); } @Override protectedvoid onPause(){ super.onPause(); Wearable.DataApi.removeListener(mGoogleApiClient,this); mGoogleApiClient.disconnect(); } @Override publicvoidonDataChanged(DataEventBuffer dataEvents){ for(DataEventevent: dataEvents){ if(event.getType()==DataEvent.TYPE_CHANGED){ // DataItem changed DataItem item =event.getDataItem(); if(item.getUri().getPath().compareTo(\"/count\")==0){ DataMap dataMap =DataMapItem.fromDataItem(item).getDataMap(); updateCount(dataMap.getInt(COUNT_KEY)); } }elseif(event.getType()==DataEvent.TYPE_DELETED){ // DataItem deleted } } } // Our method to update the count privatevoid updateCount(int c){...} ... } This activity implements the DataItem.DataListener interface. This activity adds itself as a listener for data item events inside the onConnected()method and removes the listener in the onPause() method.

You can also implement the listener as a service. For more information, see Listen for Data Layer Events.

Transferring Assets PreviousNext This lesson teaches you to .

Transfer an Asset

.

Receive an Asset

To send large blobs of binary data over the Bluetooth transport, such as images, attach anAsset to a data item and the put the data item into the replicated data store.

Assets automatically handle caching of data to prevent retransmission and conserve Bluetooth bandwidth. A common pattern is for a handheld app to download an image, shrink it to an appropriate size for display on the wearable, and transmit it to the wearable app as an asset. The following examples demonstrate this pattern.

Note: Although the size of data items is limited to 100KB, assets can be as large as desired. However, transferring large assets affects the user experience in many cases, so test your apps to ensure that they perform well if you're transferring large assets.

Transfer an Asset

Create the asset using one of the create...() methods in the Asset class. Here, we convert a bitmap to a byte stream and then call createFromBytes()to create the asset.

privatestaticAsset createAssetFromBitmap(Bitmap bitmap){ finalByteArrayOutputStream byteStream =newByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG,100, byteStream); returnAsset.createFromBytes(byteStream.toByteArray()); } When you have an asset, attach it to a data item with the putAsset() method in DataMap or PutDataRequest and then put the data item into the data store with putDataItem(): Using PutDataRequest

Bitmap bitmap =BitmapFactory.decodeResource(getResources(), R.drawable.image); Asset asset = createAssetFromBitmap(bitmap); PutDataRequest request =PutDataRequest.create(\"/image\"); request.putAsset(\"profileImage\", asset); Wearable.DataApi.putDataItem(mGoogleApiClient, request); Using PutDataMapRequest

Bitmap bitmap =BitmapFactory.decodeResource(getResources(), R.drawable.image); Asset asset = createAssetFromBitmap(bitmap); PutDataMapRequest dataMap =PutDataMapRequest.create(\"/image\"); dataMap.getDataMap().putAsset(\"profileImage\", asset) PutDataRequest request = dataMap.asPutDataRequest(); PendingResult pendingResult =Wearable.DataApi .putDataItem(mGoogleApiClient, request); Receive assets

When an asset is created, you probably want to read and extract it on other side of the connection. Here's an example of how to implement the callback to detect an asset change and extract the asset:

@Override publicvoid onDataChanged(DataEventBuffer dataEvents){ for(DataEventevent: dataEvents){ if(event.getType()==DataEvent.TYPE_CHANGED && event.getDataItem().getUri().getPath().equals(\"/image\")){ DataMapItem dataMapItem =DataMapItem.fromDataItem(event.getDataItem()); Asset profileAsset = dataMapItem.getDataMap().getAsset(\"profileImage\"); Bitmap bitmap = loadBitmapFromAsset(profileAsset); // Do something with the bitmap } } } publicBitmap loadBitmapFromAsset(Asset asset){ if(asset ==null){ thrownewIllegalArgumentException(\"Asset must be non-null\"); } ConnectionResult result = mGoogleApiClient.blockingConnect(TIMEOUT_MS,TimeUnit.MILLISECONDS); if(!result.isSuccess()){ returnnull; } // convert asset into a file descriptor and block until it's ready InputStream assetInputStream =Wearable.DataApi.getFdForAsset( mGoogleApiClient, asset).await().getInputStream(); mGoogleApiClient.disconnect(); if(assetInputStream ==null){ Log.w(TAG,\"Requested an unknown Asset.\"); returnnull; } // decode the stream into a bitmap returnBitmapFactory.decodeStream(assetInputStream); } Sending and Receiving Messages PreviousNext This lesson teaches you to . .

Send a Message Receive a Message

Try it out

FindMyPhone

You send messages using the MessageApi and attach the following items to the message:

An arbitrary payload (optional)

 A path that uniquely identifies the message's action

Unlike with data items, there is no syncing between the handheld and wearable apps. Messages are a one-way communication mechanism that's good for remote procedure calls (RPC), such as sending a message to the wearable to start an activity.

Multiple wearable devices can be connected to a user’s handheld device. Each connected device in the network is considered a node. With multiple connected devices, you must consider which nodes receive the messages. For example, in a voice transcription app that receives voice data on the wearable device, you should send the message to a node with the processing power and battery capacity to handle the request, such as a handheld device.

Note: With versions of Google Play services prior to 7.3.0, only one wearable device could be connected to a handheld device at a time. You may need to update your existing code to take the multiple connected nodes feature into consideration. If you don’t implement the changes, your messages may not get delivered to intended devices.

Send a Message

A wearable app can provide functionality for users such as voice transcription. Users can speak into their wearable device's microphone, and have a

transcription saved to a note. Since a wearable device typically does not have the processing power and battery capacity required to handle the voice transcription activity, the app should offload this work to a more capable, connected device.

The following sections show you how to advertise device nodes that can process activity requests, discover the nodes capable of fulfilling a requested need, and send messages to those nodes.

Advertise capabilities

To launch an activity on a handheld device from a wearable device, use the MessageApi class to send the request. Since multiple wearables can be connected to the handheld device, the wearable app needs to determine that a

connected node is capable of launching the activity. In your handheld app, advertise that the node it runs on provides specific capabilities. To advertise the capabilities of your handheld app:

1.

Create an XML configuration file in the res/values/ directory of your project and name it wear.xml.

2. 3.

Add a resource named android_wear_capabilities to wear.xml.

Define capabilities that the device provides.

Note: Capabilities are custom strings that you define and must be unique within your app.

The following example shows how to add a capability named voice_transcription to wear.xml:

voice_transcription Retrieve the nodes with the required capabilities

Initially, you can detect the capable nodes by calling

the CapabilityApi.getCapability() method. The following example shows how to

manually retrieve the results of reachable nodes with the voice_transcription capability:

privatestaticfinalString VOICE_TRANSCRIPTION_CAPABILITY_NAME =\"voice_transcription\"; privateGoogleApiClient mGoogleApiClient; ... privatevoid setupVoiceTranscription(){ CapabilityApi.GetCapabilityResult result = Wearable.CapabilityApi.getCapability( mGoogleApiClient, VOICE_TRANSCRIPTION_CAPABILITY_NAME, CapabilityApi.FILTER_REACHABLE).await(); updateTranscriptionCapability(result.getCapability()); } To detect capable nodes as they connect to the wearable device, register a CapabilityApi.CapabilityListener() instance to your GoogleApiClient. The following example shows how to register the listener and retrieve the results of reachable nodes with the voice_transcription capability:

privatevoid setupVoiceTranscription(){ ... CapabilityApi.CapabilityListener capabilityListener = newCapabilityApi.CapabilityListener(){ @Override publicvoid onCapabilityChanged(CapabilityInfo capabilityInfo){ updateTranscriptionCapability(capabilityInfo); } }; Wearable.CapabilityApi.addCapabilityListener( mGoogleApiClient, capabilityListener, VOICE_TRANSCRIPTION_CAPABILITY_NAME); } Note: If you create a service that extends WearableListenerService to detect capability changes, you may want to override theonConnectedNodes() method to listen to finer-grained connectivity details, such as when a wearable device switches from Wi-Fi to a Bluetooth connection to the handset. For an example implementation, see the DisconnectListenerService class in

the FindMyPhone sample. For more information on how to listen for important events, see Listen for Data Layer Events.

After detecting the capable nodes, determine where to send the message. You should pick a node that is in close proximity to your wearable device to minimize message routing through multiple nodes. A nearby node is defined as one that is directly connected to the device. To determine if a node is nearby, call the Node.isNearby() method.

The following example shows how you might determine the best node to use:

privateString transcriptionNodeId =null; privatevoid updateTranscriptionCapability(CapabilityInfo capabilityInfo){ Set connectedNodes = capabilityInfo.getNodes(); transcriptionNodeId = pickBestNodeId(connectedNodes); } privateString pickBestNodeId(Set nodes){ String bestNodeId =null; // Find a nearby node or pick one arbitrarily for(Node node : nodes){ if(node.isNearby()){ return node.getId(); } bestNodeId = node.getId(); } return bestNodeId; } Deliver the message

Once you’ve identified the best node to use, send the message using the MessageApi class.

The following example shows how to send a message to the

transcription-capable node from a wearable device. Verify that the node is available before you attempt to send the message. This call is synchronous and blocks processing until the system queues the message for delivery.

Note: A successful result code does not guarantee delivery of the message. If your app requires data reliability, use DataItem objects or theChannelApi class to send data between devices.

publicstaticfinalString VOICE_TRANSCRIPTION_MESSAGE_PATH =\"/voice_transcription\"; privatevoid requestTranscription(byte[] voiceData){ if(transcriptionNodeId !=null){ Wearable.MessageApi.sendMessage(googleApiClient, transcriptionNodeId, VOICE_TRANSCRIPTION_MESSAGE_PATH, voiceData).setResultCallback( newResultCallback(){ @Override publicvoid onResult(SendMessageResult sendMessageResult){ if(!sendMessageResult.getStatus().isSuccess()){ // Failed to send message } } } ); }else{ // Unable to retrieve node with transcription capability } } Note: To learn more about asynchronous and synchronous calls to Google Play services and when to use each, see Communicate with Google Play Services. You can also broadcast messages to all connected nodes. To retrieve all of the connected nodes that you can send messages to, implement the following code:

privateCollection getNodes(){ HashSetresults =newHashSet(); NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await(); for(Node node : nodes.getNodes()){ results.add(node.getId()); } return results; } Receive a Message

To be notified of received messages, implement the MessageListener interface to provide a listener for message events. Then, register the listener with the MessageApi.addListener() method. This example shows how you might

implement the listener to check the VOICE_TRANSCRIPTION_MESSAGE_PATH. If this condition is true, start an activity to process the voice data.

@Override publicvoid onMessageReceived(MessageEvent messageEvent){ if(messageEvent.getPath().equals(VOICE_TRANSCRIPTION_MESSAGE_PATH)){ Intent startIntent =newIntent(this,MainActivity.class); startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startIntent.putExtra(\"VOICE_DATA\", messageEvent.getData()); startActivity(startIntent); } } This is just a snippet that requires more implementation details. Learn about how to implement a full listener service or activity in Listening for Data Layer Events.

Handling Data Layer Events PreviousNext This lesson teaches you to . .

Wait for the Status of Data Layer Calls Listen for Data Layer Events

When you make calls to the Data Layer API, you can receive the status of the call when it completes as well as listen for any changes that the call ends up making with listeners.

Wait for the Status of Data Layer Calls

You'll notice that calls to the Data Layer API sometimes return a PendingResult, such asputDataItem(). As soon as the PendingResult is created, the operation is queued in the background. If you do nothing else after this, the operation eventually completes silently. However, you'll usually want to do something with the result after the operation completes, so the PendingResult lets you wait for the result status, either synchronously or asynchronously.

Asynchronous calls

If your code is running on the main UI thread, do not make blocking calls to the Data Layer API. You can run the calls asynchronously by adding a callback method to the PendingResult object, which fires when the operation is completed:

pendingResult.setResultCallback(newResultCallback(){ @Override publicvoid onResult(finalDataItemResult result){ if(result.getStatus().isSuccess()){ Log.d(TAG,\"Data item set: \"+ result.getDataItem().getUri()); } } }); Synchronous calls

If your code is running on a separate handler thread in a background service (which is the case in a WearableListenerService), it's fine for the calls to block. In this case, you can call await() on the PendingResult object, which blocks until the request completes and returns a Result object:

DataItemResult result = pendingResult.await(); if(result.getStatus().isSuccess()){ Log.d(TAG,\"Data item set: \"+ result.getDataItem().getUri()); } Listen for Data Layer Events

Because the data layer synchronizes and sends data across the handheld and wearable, it is usually necessary to listen for important events. Examples of such events include creation of data items and receipt of messages. To listen for data layer events, you have two options:

 Create a service that extends WearableListenerService.

 Create an activity that implements DataApi.DataListener.

With both these options, you override the data event callback methods for the events you are interested in handling.

With a WearableListenerService

You typically create instances of this service in both your wearable and handheld apps. If you are not interested in data events in one of these apps, then you don't need to implement this service in that particular app. For example, you can have a handheld app that sets and gets data item objects and a wearable app that listens for these updates to update its UI. The wearable never updates any of the data items, so the handheld app doesn't listen for any data events from the wearable app.

Some of the events you can listen for using WearableListenerService are as follows:

 onDataChanged(): Whenever a data item object is created, deleted, or

changed, the system triggers this callback on all connected nodes.

 onMessageReceived(): A message sent from a node triggers this callback

on the target node.

 onCapabilityChanged(): When a capability that an instance of your app

advertises becomes available on the network, that event triggers this callback. If you're looking for a nearby node you can query the isNearby() method of the nodes provided in the callback. In addition to those on this list, you can listen for events from ChannelApi.ChannelListener, such as onChannelOpened(). To create a WearableListenerService, follow these steps:

1. 2. 3.

Create a class that extends WearableListenerService.

Listen for the events that you're interested in, such as onDataChanged().

Declare an intent filter in your Android manifest to notify the system about your WearableListenerService. This declaration allows the system to bind your service as needed.

The following example shows how to implement a simple WearableListenerService:

publicclassDataLayerListenerServiceextendsWearableListenerService{ privatestaticfinalString TAG =\"DataLayerSample\"; privatestaticfinalString START_ACTIVITY_PATH =\"/start-activity\"; privatestaticfinalString DATA_ITEM_RECEIVED_PATH =\"/data-item-received\"; @Override publicvoid onDataChanged(DataEventBuffer dataEvents){ if(Log.isLoggable(TAG,Log.DEBUG)){ Log.d(TAG,\"onDataChanged: \"+ dataEvents); } finalList events =FreezableUtils .freezeIterable(dataEvents); GoogleApiClient googleApiClient =newGoogleApiClient.Builder(this) .addApi(Wearable.API) .build(); ConnectionResult connectionResult = googleApiClient.blockingConnect(30,TimeUnit.SECONDS); if(!connectionResult.isSuccess()){ Log.e(TAG,\"Failed to connect to GoogleApiClient.\"); return; } // Loop through the events and send a message // to the node that created the data item. for(DataEventevent: events){ Uri uri =event.getDataItem().getUri(); // Get the node id from the host value of the URI String nodeId = uri.getHost(); // Set the data of the message to be the bytes of the URI byte[] payload = uri.toString().getBytes(); // Send the RPC Wearable.MessageApi.sendMessage(googleApiClient, nodeId, DATA_ITEM_RECEIVED_PATH, payload); } } } The next section explains how to use an intent filter with this listener.

Using filters with WearableListenerService

An intent filter for the WearableListenerService example shown in the previous section might look like this:

In this filter, the DATA_CHANGED action replaces the previously

recommended BIND_LISTENER action so that only specific events wake or launch your application. This change improves system efficiency and reduces battery consumption and other overhead associated with your application. In this

example, the watch listens for the /start-activity data item, and the phone listens for the /data-item-received message response.

Standard Android filter matching rules apply. You can specify multiple services per manifest, multiple intent filters per service, multiple actions per filter, and multiple data stanzas per filter. Filters can match on a wildcard host or on a specific one. To match on a wildcard host, use host=\"*\". To match on a specific host, specify host=.

You can also match a literal path or path prefix. If you are matching by path or path prefix, you must specify a wildcard or specific host. If you do not do so, the system ignores the path you specified.

For more information on the filter types that Wear supports, see the API reference documentation for WearableListenerService.

For more information on data filters and matching rules, see the API reference documentation for the data manifest element.

When matching intent filters, there are two important rules to remember:

 If a scheme is not specified for the intent filter, the system ignores all the other URI attributes.

 If no host is specified for the filter, the system ignores the port attribute and all the path attributes.

With a listener activity

If your app only cares about data-layer events when the user is interacting with the app, it may not need a long-running service to handle every data change. In such a case, you can listen for events in an activity by implementing one or more of the following interfaces:

  

DataApi.DataListener MessageApi.MessageListener CapabilityApi.CapabilityListener

To create an activity that listens for data events:

1. 2.

Implement the desired interfaces.

In onCreate(), create an instance of GoogleApiClient to work with the Data Layer API.

3. 4.

In onStart(), call connect() to connect the client to Google Play services.

When the connection to Google Play services is established, the system calls onConnected().

This

is

where

you

call DataApi.addListener(),MessageApi.addListener(),

or CapabilityApi.addListener() to notify Google Play services that your activity is interested in listening for data layer events.

5.

In onStop(), unregister any listeners

with DataApi.removeListener(), MessageApi.removeListener(), or CapabilityApi.removeListener().

An alternative to adding listeners in onConnected() and removing them in onStop() is to add a filtered listener in an activity’s onResume() and remove it in onPause(), so as to only receive data that is relevant to the current application state.

6.

Implement onDataChanged(), onMessageReceived(), onCapabilityChanged(), or methods from Channel API listener methods, depending on the interfaces that you implemented.

Here's an example that implements DataApi.DataListener:

publicclassMainActivityextendsActivityimplements DataApi.DataListener,ConnectionCallbacks,OnConnectionFailedListener{ privateGoogleApiClient mGoogleApiClient; @Override protectedvoid onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); mGoogleApiClient =newGoogleApiClient.Builder(this) .addApi(Wearable.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); } @Override protectedvoid onStart(){ super.onStart(); if(!mResolvingError){ mGoogleApiClient.connect(); } } @Override publicvoid onConnected(Bundle connectionHint){ if(Log.isLoggable(TAG,Log.DEBUG)){ Log.d(TAG,\"Connected to Google Api Service\"); } Wearable.DataApi.addListener(mGoogleApiClient,this); } @Override protectedvoid onStop(){ if(null!= mGoogleApiClient && mGoogleApiClient.isConnected()){ Wearable.DataApi.removeListener(mGoogleApiClient,this); mGoogleApiClient.disconnect(); } super.onStop(); } @Override publicvoid onDataChanged(DataEventBuffer dataEvents){ for(DataEventevent: dataEvents){ if(event.getType()==DataEvent.TYPE_DELETED){ Log.d(TAG,\"DataItem deleted: \"+event.getDataItem().getUri()); }elseif(event.getType()==DataEvent.TYPE_CHANGED){ Log.d(TAG,\"DataItem changed: \"+event.getDataItem().getUri()); } } } } Using Filters with Listener Activities

Just as you can specify intent filters for

manifest-based WearableListenerService objects, you can also use intent filters when registering a listener through the Wearable API. The same rules are applicable to both API-based listeners manifest-based listeners.

A common pattern is to register a listener with a specific path or path prefix in an activity’sonResume() method, and to remove the listener in the

activity’s onPause() method. Implementing listeners in this fashion allows your application to more selectively receive events, improving its design and efficiency.

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- efsc.cn 版权所有

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务