This can be done using the specified MessageApi: http://developer.android.com/training/wearables/data-layer/messages.html
You need to initialize and connect to GoogleApiClient. After clicking the button, you should get a list of nodes and send them a message. The last step is to read this message in the phone application part, this can be done by registering the proper WearableListenerService. See the sample code below.
Wearable part of the application:
Please define such activity in your Wearable part of the application:
public class WearableButtonActivity extends Activity { private GoogleApiClient mGoogleApiClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.wearable_button_activity); mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Wearable.API) .build(); mGoogleApiClient.connect(); } public void onButtonClicked(View target) { if (mGoogleApiClient == null) return; final PendingResult<NodeApi.GetConnectedNodesResult> nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient); nodes.setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() { @Override public void onResult(NodeApi.GetConnectedNodesResult result) { final List<Node> nodes = result.getNodes(); if (nodes != null) { for (int i=0; i<nodes.size(); i++) { final Node node = nodes.get(i);
and apply the onButtonClick method to your button in res / layout / wearable_button_activity.xml:
<Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click me!" android:layout_gravity="center" android:onClick="onButtonClicked" />
OR just install OnClickListener from the code if you like it:
findViewById(R.id.button).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onButtonClicked(v); } });
Phone part of the application:
Then declare a DataLayerListenerService on your phone manifest:
<service android:name=".DataLayerListenerService" > <intent-filter> <action android:name="com.google.android.gms.wearable.BIND_LISTENER" /> </intent-filter> </service>
Class DataLayerListenerService:
public class DataLayerListenerService extends WearableListenerService { @Override public void onMessageReceived(MessageEvent messageEvent) { super.onMessageReceived(messageEvent); if("/MESSAGE".equals(messageEvent.getPath())) {
IMPORTANT: both parts of your application must have the same package name in order to communicate with each other.
source share