標籤:
http://developer.android.com/training/wearables/data-layer/events.html
以下是本人在學習官方開發文檔時的筆記,主要是翻譯為主,並在中間會插入一些自己的總結與研究,希望對讀者有所協助.
本文分為2大部分:
Section1 : 如何擷取資料通訊的結果.
Section2 : 如何監聽資料層中的資料事件.
其中Section2分為2模組:
1. 繼承WearableListenerService;
2. Activity實現資料介面.
Section 1 : Wait for the Status of Data Layer Calls- 等待資料操作結果
在進行資料通訊的時候,有時候會返回一個PendingResult對象,例如調用了putDataItem方法.一旦PendingResult對象被構建了,那麼資料操作就會在後台隊列中.你可以選擇是否對這個操作結果進行處理.PendingResult對象可以讓你擷取到操作結果,無論是同步還是非同步.
Asynchronously waiting-非同步等待
若你是在UI線程中執行資料操作,那麼小心阻塞問題.在這裡可以使用回調監聽的方式來實現非同步等待:
pendingResult.setResultCallback(new ResultCallback<DataItemResult>() { @Override public void onResult(final DataItemResult result) { if(result.getStatus().isSuccess()) { Log.d(TAG, "Data item set: " + result.getDataItem().getUri()); } }});Synchronously waiting-同步等待
若你在獨立的後台服務進程中進行資料操作,那麼可以使用同步等待的方式來處理操作結果,在擷取到處理結果前都會阻塞住進程.
DataItemResult result = pendingResult.await();if(result.getStatus().isSuccess()) { Log.d(TAG, "Data item set: " + result.getDataItem().getUri());}Section 2 : Listen for Data Layer Events- 監聽資料層事件
因為在手機和手錶的資料通訊同步的,所以通常需要監聽一些重要的事件,如資料建立,訊息接收,通訊的串連.
監聽資料通訊,可以通過以下兩種方式實現:
- 建立一個繼承自WearableListenerService的Service
- 建立一個實現了DataApi.DataListener資料介面的Activity
1.With a WearableListenerService使用情景
一般而言都會在手機端和手錶端都構建一個這樣的子類Service. 但如果哪一端對資料事件的監聽處理沒什麼需求,那一端則無需構建.
例如,你可以在手機端構建和傳遞資料給手錶,手錶則監聽這些資料事件來更新自身介面.但手錶端只是單方面的擷取資料,不會對資料進行做任何修改,那麼,手機端則無需監聽資料通訊事件.
方法介紹
接下來是介紹WearableListenerService的一些重要事件方法:
- onDataChanged() :增,刪,改,這三種事件都會調用這個介面.並且是兩端都會被觸發調用.→雙向
- onMessageReceived():訊息從一端發送,會調用另一端的介面.→單向
- onPeerConnected() , onPeerDisconnected():當兩端進行串連或者斷開的時候會觸發.改變一端的串連狀態都會調用兩端的介面.→雙向
實現步驟
- 繼承WearableListenerService
- 監聽資料通訊事件
- 在Manifest中聲明,並添加intent filter監聽com.google.android.gms.wearable.BIND_LISTENER這個動作
代碼範例
public class DataLayerListenerService extends WearableListenerService { private static final String TAG = "DataLayerSample"; private static final String START_ACTIVITY_PATH = "/start-activity"; private static final String DATA_ITEM_RECEIVED_PATH = "/data-item-received"; @Override public void onDataChanged(DataEventBuffer dataEvents) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "onDataChanged: " + dataEvents); } final List events = FreezableUtils .freezeIterable(dataEvents); GoogleApiClient googleApiClient = new GoogleApiClient.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 (DataEvent event : 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); } }}
註解 :
-
final List events = FreezableUtils .freezeIterable(dataEvents);
這裡的作用是通過工具類FreezableUtils將資料對象dataEvents轉換成不可修改的類型,以避免在處理資料的過程中,資料發生改變.
-
ConnectionResult connectionResult = googleApiClient.blockingConnect(30, TimeUnit.SECONDS);
阻塞當前線程,在30秒內擷取串連狀態,否則視為逾時串連.因為onDataChange屬於非同步線程中,所以這裡不會導致主線程阻塞.注意區分,這裡是擷取和googleApiClient的串連,而Section One中是發送資料的結果.
Manifest聲明
<service android:name=".DataLayerListenerService"> <intent-filter> <action android:name="com.google.android.gms.wearable.BIND_LISTENER" /> </intent-filter></service>
Permissions within Data Layer Callbacks
注意點
資料回調介面中的許可權問題
為了回調資料事件介面,Google Play會綁定你的Service並且通過IPC的方式調用.這也導致了你的回調介面繼承了調用進程的許可權.
若想要在回調介面中做某些特權操作,你會發現安全驗證失敗了,你會發現回調介面中列印出來的進程id,是在觸發回調介面的進程的id,而不是你的應用的進程.
為瞭解決這個問題,先調用clearCallingIdentity()來重設id,恢複為應用進程id;再執行你所需要的操作;最後再調用恢複為restoreCallingIdentity()調用者的id.
long token = Binder.clearCallingIdentity();try { performOperationRequiringPermissions();} finally { Binder.restoreCallingIdentity(token);}WearableListenerService的深入研究:
以下關於生命週期的測試環境是在模擬器上,在其他環境上可能略有差異.
- 生命週期 :完全由Android Wear控制 !
- 前提 : 在Manifest中進行了聲明,監聽了com.google.android.gms.wearable.BIND_LISTENER這個Action
- 現象 : 在手錶和手機斷開的情況下,安裝了Demo,Service沒有調用onCreate方法.當串連上,則立即調用onCreate方法.
- 生命週期流程:
串連手機 : onCreate > onPeerConnected
操作過程 : 若Service沒有接收到訊息,以最後一次被回調為準,約8~12秒左右後會自殺,調用onDestroy.
斷開手機 : 若Service已死 : onCreate > onPeerDisconnected > onDestroy(等待8~12秒);若Service處於活躍狀態,則調用後面2個方法.
- 自身已經實現了DataApi.DataListener,MessageApi.MessageListener,NodeApi.NodeListener這3個介面.
總結 :
1.WearableListenerService是由Android Wear控制; 2.生命週期較短,在停止操作8~12秒內消亡 3.不能理解為手機端和手錶端的串連,而應該是理解為監聽這個串連 : 因為斷開兩端的串連,不會立刻調用onDestroy方法 4.在串連後台發生狀態改變,會被立即地建立,調用回調介面,以處理應用業務
2.With a Listener Activity方法介紹
若你的應用只是需要在使用者開啟時監聽資料通訊事件,而不需要在後台監聽資料改變,那麼可以實現以下介面來實現你的需求.
- DataApi.DataListener
- MessageApi.MessageListener
- NodeApi.NodeListener
實現步驟
接下來是建立一個監聽資料通訊事件的Activity
- 實現介面 : 實現上面列舉的介面(根據需求來定,不需要全部都實現)
- 建立服務物件 : 在onCreate方法中建立一個GoogleApiClient對象來實現與資料通訊的串連.
- 串連服務 : 在onStart方法中調用GoogleApiClient的connect方法來串連服務
- 註冊監聽器 : 當GoogleApiClient串連上了服務,會回調onConnected方法,那麼我們就可以在這裡中註冊監聽器,來監聽我們所關心的通訊事件.
- 反註冊監聽器,並斷開服務 : 在onStop方法中,反註冊之前註冊的監聽器,然後再斷開GoogleApiClient服務串連.
- 實現事件回調介面 : 根據註冊的監聽器實現介面,處理相關的需求.
代碼範例
以下是一個實現了DataApi.DataListener的範例:
public class MainActivity extends Activity implements DataApi.DataListener, ConnectionCallbacks, OnConnectionFailedListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Wearable.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); } @Override protected void onStart() { super.onStart(); if (!mResolvingError) { mGoogleApiClient.connect(); } } @Override public void onConnected(Bundle connectionHint) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Connected to Google Api Service"); } Wearable.DataApi.addListener(mGoogleApiClient, this); } @Override protected void onStop() { if (null != mGoogleApiClient && mGoogleApiClient.isConnected()) { Wearable.DataApi.removeListener(mGoogleApiClient, this); mGoogleApiClient.disconnect(); } super.onStop(); } @Override public void onDataChanged(DataEventBuffer dataEvents) { for (DataEvent event : dataEvents) { if (event.getType() == DataEvent.TYPE_DELETED) { Log.d(TAG, "DataItem deleted: " + event.getDataItem().getUri()); } else if (event.getType() == DataEvent.TYPE_CHANGED) { Log.d(TAG, "DataItem changed: " + event.getDataItem().getUri()); } } }
Android Wear開發 - 資料通訊 - 第三節 : 事件處理