標籤:android 穿戴式裝置 wear 資料
Android Wear 資料同步機制總結
當手機與手錶建立藍芽串連之後,資料就可以通過Google Play Service進行傳輸。
同步資料對象Data Item
DataItem提供手機與手錶資料存放區的自動同步,一個DataItem對象由其建立者與路徑組成的URI所確定。一個DataItem對象為手機和手錶提供了一個資料通路,開發人員通過改變指定的DataItem實現手機和手錶的資料自動同步。
訪問資料層API
DataItem可以提供手機和手錶資料的儲存,改變該對象的操作則依賴資料層API(the Data Layer APIs),也就是說,在改變DataItem資料之前,需要先訪問資料層,獲得一個GoogleApiClient執行個體,從而能夠使用資料層API。
下面是執行個體化GoogleApiClient的代碼
GoogleApiClient mGoogleAppiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(new ConnectionCallbacks() { @Override public void onConnected(Bundle connectionHint) { Log.d(TAG, "onConnected: " + connectionHint); // Now you canuse the data layer API } @Override public void onConnectionSuspended(int cause) { Log.d(TAG, "onConnectionSuspended: " + cause); } }) .addOnConnectionFailedListener(new OnConnectionFailedListener() { @Override public void onConnectionFailed(ConnectionResult result) { Log.d(TAG, "onConnectionFailed: " + result); } }) .addApi(Wearable.API) .build();
在使用資料層Api的之前,需要先調用connect()方法,如果成功則會回調onConnected()方法,否則回調onConnectionFailed()。
同步DataItems
GoogleApiClient串連成功後,就可以通過DataItem進行資料同步了。
一個DataItem包括連個部分,一個是Payload,這是一個位元組數組,可以通過序列化或者還原序列化儲存需要的資料類型和對象;另一個是Path,這是一個唯一的字串,由反斜線開頭,區別不同的DataItem。
通常在開發過程中是使用DataMap類實現DataItem介面,類似Bundle鍵值對的儲存方式。
下面是使用的DataMap步驟:
1、 建立PutDataMapRequest對象,為DataItem設定path值;
2、 使用put…()方法為DataMap設定需要的資料;
3、 調用PutDataMapRequest.asPutDataRequest()建立PutDataRequest對象;
4、 調用DataApi.putDataItem()請求系統建立DataItem。
如果此時手機和手錶沒有建立串連,則會將資料儲存在Buffer中,等下次串連後會發送到另一方。
下面是使用DataMap建立DataItem的方法
PutDataMapRequest dataMap = PutDataMapRequest.create("/count");dataMap.getDataMap().putInt(COUNT_KEY, count++);PutDataRequest request = dataMap.asPutDataRequest();PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi .putDataItem(mGoogleApiClient, request);
監聽資料層事件
由於資料層同步或發送的資料連線手機和手錶,所以經常需要獲知何時DataItem被建立以及手機與手錶什麼時候串連或斷開等事件。
監聽資料層時間可以使用兩種方式,一種是繼承WearableListenerService,一種是在Activity中實現DataApi.DataListener。無論使用兩種方式的哪種,可以重寫其需要的回調方法執行相應的操作。
1、 使用WearableListenerService
該service在手機和手錶端都可以使用,如果在一方不需要監聽資料層時間可以不適用該服務。
例如,可以在手機端接收和設定DataItem,然後在手錶端實現該服務,監聽資料層的事件,從而修改手錶的UI。
WearableListenerService提供回調介面onDataChanged()處理DataItem的變化,當DataItem被建立、更改或刪除,手機和手錶的該事件將被觸發。
下面是使用WearableListenerService的方法
1、 建立一個類繼承WearableListenerService;
2、 監聽需要的事件,如onDataChanged();
3、 在設定檔中聲明一個intentfilter通知系統監聽WearableListenerService,這樣在系統需要的時候就會綁定WearableListenerService。
下面代碼是一個簡單的WearableListenerService實現。
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); } }}
下面代碼是設定檔中聲明的intentfilter
<service android:name=".DataLayerListenerService"> <intent-filter> <action android:name="com.google.android.gms.wearable.BIND_LISTENER" /> </intent-filter></service>
使用DataApi.DataListener監聽資料層
如果不需要後台長時間進行監聽,可以使用DataApi.DataListener進行監聽,下面是使用該方式的方法。
1、 使用DataApi.DataListener介面
2、 在onCreate中建立 GoogleApiClient,訪問資料層API
3、 在onStart中調用connect()串連Google PlayService
4、 但串連上GooglePlay Service後,系統調用onConnected(),通知Google Play service該activity監聽資料層事件
5、 在onStop中調用DataApi.removeListener()
6、 實現 onDataChanged()回調
下面是使用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提供了一個服務類介面NotificationListenerService,繼承該服務,可以擷取手機中應用發起的通知,在設定檔中需要添加如下聲明和許可權
<service android:name=".NotificationListener" android:label="@string/service_name" android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"> <intent-filter> <action android:name="android.service.notification.NotificationListenerService" /> </intent-filter> </service>
這樣在系統設定中會出現一個是否允許該服務捕獲通知的選項,在設定--安全與隱私--通知讀取許可權
該服務有兩個抽象方法需要實現,分別是當有通知發起與通知被銷毀,都會觸發其回調方法。
public class NotificationCollectorService extends NotificationListenerService { @Override public void onNotificationPosted(StatusBarNotification sbn) { } @Override public void onNotificationRemoved(StatusBarNotification sbn) { } }
也就是說當系統發現某應用產生通知或者使用者刪除某通知,都會回調該服務的這兩個函數,函數的參數StatusBarNotification包含著該通知的具體資訊。
如果是在Android Wear開發中,使用該方法捕獲手機的通知,然後同步到手錶中,就是使用該服務進行的中轉。
通知同步
接收到的通知以StatusBarNotification對象形式傳遞給回呼函數onNotificationPosted(),
調用StatusBarNotification對象的公用方法,分別取出StatusBarNotification中的PackageName、Tag、Id、notification對象和PostTime,通過這些值去建立DataItem。