2016-07-23 115 views
0

我有一個錶盤,我正在尋找使用數據層發送幾個字符串。我通過將該服務添加到清單並創建DataLayerListenerService類來遵循guide通過WearableListenerService將數據發送到手機可穿戴

我該怎麼做才能將數據發送到服務的可穿戴設備?我已經在我的配置活動中使用PutDataRequest之前完成了這個工作。我現在想定期向可穿戴設備發送電池統計數據,天氣信息等。我該怎麼做呢?

這是到目前爲止我的類別:

public class DataLayerListenerService extends WearableListenerService { 

private static final String TAG = DataLayerListenerService.class.getSimpleName(); 
public static final String EXTRAS_PATH = "/extras"; 
private static final String START_ACTIVITY_PATH = "/start-activity"; 
private static final String DATA_ITEM_RECEIVED_PATH = "/data-item-received"; 
private GoogleApiClient mGoogleApiClient; 

public static void LOGD(final String tag, String message) { 
    if (Log.isLoggable(tag, Log.DEBUG)) { 
     Log.d(tag, message); 
    } 
} 

@Override 
public void onCreate() { 
    super.onCreate(); 
    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addApi(Wearable.API) 
      .build(); 
    mGoogleApiClient.connect(); 
} 

@Override 
public void onDataChanged(DataEventBuffer dataEvents) { 
    LOGD(TAG, "onDataChanged: " + dataEvents); 
    if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting()) { 
     ConnectionResult connectionResult = mGoogleApiClient 
       .blockingConnect(30, TimeUnit.SECONDS); 
     if (!connectionResult.isSuccess()) { 
      Log.e(TAG, "DataLayerListenerService failed to connect to GoogleApiClient, " 
        + "error code: " + connectionResult.getErrorCode()); 
      return; 
     } 
    } 

    // Loop through the events and send a message back to the node that created the data item. 
    for (DataEvent event : dataEvents) { 
     Uri uri = event.getDataItem().getUri(); 
     String path = uri.getPath(); 
     if (EXTRAS_PATH.equals(path)) { 
      // Get the node id of the node that created the data item from the host portion 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(mGoogleApiClient, nodeId, DATA_ITEM_RECEIVED_PATH, 
        payload); 
     } 
    } 
} 

回答

1

首先,創建一個GoogleApiClient例如,當你想在谷歌Play服務庫提供的谷歌API之一的連接。您需要創建一個GoogleApiClient實例(「Google API Client」)。 Google API客戶端爲所有Google Play服務提供了一個通用入口點,並管理用戶設備與每項Google服務之間的網絡連接。

定義一個WearableListenerService它收到message。它接收來自其他節點的事件,如數據更改,消息或連接事件。

發送消息到MessageApi,消息被傳遞到連接的網絡節點。多個可穿戴設備可以連接到用戶的手持設備。網絡中的每個連接的設備都被視爲一個節點。對於多個連接的設備,您必須考慮哪些節點接收消息。

然後執行MessageApi.MessageListeneraddListener(GoogleApiClient, MessageApi.MessageListener)一起使用來接收消息事件。希望在後臺通知事件的呼叫者應使用WearableListenerService。然後,接收消息並使用LocalBroadcastManager來詳細說明消息並顯示消耗的值。

下面是相關的SO票:Send message from wearable to phone and then immediately reply

相關問題