Pages

Android Wear (Send message from android wear to phone)

In this post, I will show how to send the sensor data in android wear to phone. (Continue from Android Wear API (Check Android Wear Sensor eventListener)

I referenced the Data Layer Messages.


The figure shows the message flow. You can refer the Data Layer Messages for sending message from phone to wearable device.

First, I start with mobile part.

build.gradle(Module:wear)

I added more depencies.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.google.android.support:wearable:2.0.0'
    compile 'com.google.android.gms:play-services-wearable:11.0.4'
    provided 'com.google.android.wearable:wearable:1.0.0'
//for message api, we need google service.
    compile 'com.google.android.gms:play-services:11.0.4'

}

//I added the service to receive the message from wear
moblie/manifests/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lee.helloworld">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.BODY_SENSORS" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.wearable.standalone"
            android:value="true" />
//add meta-data for google service.
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

//I added "ListenerService". you can make new service like creating new java class
//Or, Alt+Enter and create class
        <service android:name=".ListenerService">
            <intent-filter>
                <action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
            </intent-filter>
        </service>
    </application>

</manifest>



mobile/java/ListenerService.java


import android.app.Service;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.WearableListenerService;

public class ListenerService extends WearableListenerService {

    @Override
    public void onMessageReceived(MessageEvent messageEvent) {

        if (messageEvent.getPath().equals("/message_path")) {
            final String message = new String(messageEvent.getData());
        }
        else {
            super.onMessageReceived(messageEvent);
        }
        if (messageEvent.getPath().equals("/message_path")) {
            final String message = new String(messageEvent.getData());
            Intent messageIntent = new Intent();
            messageIntent.setAction(Intent.ACTION_SEND);
            messageIntent.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);
        } else {
            super.onMessageReceived(messageEvent);
        }
    }
}

Now, we will add more code in the MainActivity in mobile to receive message from wear.

mobile/java/MainActivity.java


public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, DataApi.DataListener {
//Need Google API for message api
    private GoogleApiClient mGoogleApiClient;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView)findViewById(R.id.tv);

        mGoogleApiClient=new GoogleApiClient.Builder(this).addApi(Wearable.API).
                addConnectionCallbacks(this).
                addOnConnectionFailedListener(this).build();
//message filter
        IntentFilter messageFilter = new IntentFilter(Intent.ACTION_SEND);
        MessageReceiver messageReceiver = new MessageReceiver();
        LocalBroadcastManager.getInstance(this).registerReceiver(messageReceiver, messageFilter);

    }
//receive message
    public class MessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String message = intent.getStringExtra("message");
            // Display message in UI
            textViewv.setText(message);
        }
    }

    @Override
    protected void onStart(){
        super.onStart();
//init mGoogleApiClient
        mGoogleApiClient.connect();
    }
   protected void onStop() {
        Wearable.DataApi.removeListener(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
        super.onStop();
    }


    @Override
    public void onDataChanged(DataEventBuffer dataEventBuffer) {
        Log.d("data change","onDataChagned");
        final List<DataEvent> events= FreezableUtils.freezeIterable(dataEventBuffer);
        dataEventBuffer.close();
        for(final DataEvent event: events){
              if(event.getType() == DataEvent.TYPE_CHANGED){
                  runOnUiThread(new Runnable(){
                      @Override
                      public void run(){
                          textViewv.setText(event.getDataItem().getUri()+" data:" + event.getDataItem().getData().toString());
                          Log.d("data change",event.getDataItem().getUri()+" data:" + event.getDataItem().getData().toString());

                      }
                  });

              }

        }

    }
}


Now, we move to the wear part.

wear/manifest/androidManifest.xml
//add meta-data like androidManifest.xml in mobile
 <meta-data android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>


build.gradle(Module:wear)
//add compile like build.gradle(Module:mobile)
    compile 'com.google.android.gms:play-services:11.0.4'


If you got error message at the compile, press Alt+Enter and change version.

Now, we start from the previous post Android Wear API Android Wear API (Check Android Wear Sensor eventListener ).

wear/java/MainActivity.java

public class MainActivity extends WearableActivity implements SensorEventListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    private static final SimpleDateFormat AMBIENT_DATE_FORMAT =
            new SimpleDateFormat("HH:mm", Locale.US);

    private BoxInsetLayout mContainerView;
    private TextView mTextView;
    private TextView mClockView;
    SensorManager mSensorManager;
  //Google API
    GoogleApiClient mGoogleApiClient;
    // Add Sensor and Listener to Recieve data from the sensor
    Sensor mGyroscopeSensor;
   SensorEventListener sensorEventListener;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setAmbientEnabled();

        mContainerView = (BoxInsetLayout) findViewById(R.id.container);
        mTextView = (TextView) findViewById(R.id.text);
        mClockView = (TextView) findViewById(R.id.clock);
     
        mGoogleApiClient=new GoogleApiClient.Builder(this).addApi(Wearable.API).
                addConnectionCallbacks(this).
                addOnConnectionFailedListener(this).build();

        mSensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE));
        mGyroscopeSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
// 0:x 1:y 2:z
mSensorManager.registerListener(this, mGyroscopeSensor, SensorManager.SENSOR_DELAY_NORMAL);

}

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }
    public void onSensorChanged(SensorEvent sensorEvent) {
new SendToDataLayerThread("/message_path", sensorEvent.sensor.getName() +" : " + (int) sensorEvent.values[0]).start();
   }

   class SendToDataLayerThread extends Thread {
        String path;
        String message;

        // Constructor to send a message to the data layer
        SendToDataLayerThread(String p, String msg) {
            path = p;
            message = msg;
        }
        public void run() {
            NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await();
            for (Node node : nodes.getNodes()) {
                MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), path, message.getBytes()).await();
                if (result.getStatus().isSuccess()) {
                    Log.v("myTag", "Message: {" + message + "} sent to: " + node.getDisplayName());
                }
                else {
                    // Log an error
                    Log.v("myTag", "ERROR: failed to send Message");
                }
            }
        }
    }

   protected void onStop() {
        mGoogleApiClient.disconnect();
        super.onStop();
    }
}


Thank you for reading my post. I hope that you find some of this information useful.



Share:

No comments:

Post a Comment

Powered by Blogger.

Popular Posts