Sending data to android wear device
Asked Answered
E

1

5

I'm trying to send a String array from my phone to my wear, I've created a service on my phone that is supposed to send the data with this code :

public class SendDataService extends Service {

private static final String TAG = "SendDataService";

@Override
public void onCreate(){
    GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(Bundle connectionHint) {
                    Log.d(TAG, "onConnected: " + connectionHint);
                    // Now you can use the data layer API
                }
                @Override
                public void onConnectionSuspended(int cause) {
                    Log.d(TAG, "onConnectionSuspended: " + cause);
                }
            })
            .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(ConnectionResult result) {
                    Log.d(TAG, "onConnectionFailed: " + result);
                }
            })
            .addApi(Wearable.API)
            .build();
    mGoogleApiClient.connect();
    String[] eventStrings = Events.eventsString(Events.readCalendarEvent(this));
    PutDataMapRequest dataMap = PutDataMapRequest.create("/events");
    dataMap.getDataMap().putStringArray("events", eventStrings);
    PutDataRequest request = dataMap.asPutDataRequest();
    PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi
            .putDataItem(mGoogleApiClient, request);
    mGoogleApiClient.disconnect();
}

and from the watch I try to get it in my main activity with this code :

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_agenda_wear);
    this.context = this;
    GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(Bundle connectionHint) {
                    Log.d(TAG, "onConnected: " + connectionHint);
                    // Now you can use the data layer API
                }
                @Override
                public void onConnectionSuspended(int cause) {
                    Log.d(TAG, "onConnectionSuspended: " + cause);
                }
            })
            .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(ConnectionResult result) {
                    Log.d(TAG, "onConnectionFailed: " + result);
                }
            })
            .addApi(Wearable.API)
            .build();
    mGoogleApiClient.connect();


    PendingResult<DataItemBuffer> results = Wearable.DataApi.getDataItems(mGoogleApiClient);
    results.setResultCallback(new ResultCallback<DataItemBuffer>() {
        @Override
        public void onResult(DataItemBuffer dataItems) {
            if (dataItems.getCount() != 0) {
                DataMapItem dataMapItem = DataMapItem.fromDataItem(dataItems.get(0));

                // This should read the correct value.
                AgendaWear.this.eventString = dataMapItem.getDataMap().getStringArray("events");
            }

            dataItems.release();
        }
    });
    mGoogleApiClient.disconnect();
    final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
    stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
        @Override
        public void onLayoutInflated(WatchViewStub stub) {
            if (AgendaWear.this.eventString == null){
                Toast.makeText(AgendaWear.this, "No data",Toast.LENGTH_LONG).show();
                AgendaWear.this.eventString = new String[0];
            }
            AgendaWear.listItems = eventArray(AgendaWear.this.eventString);
            mListView = (WearableListView) stub.findViewById(R.id.listView);
            mListView.setAdapter(new MyAdapter(AgendaWear.this));
            mListView.setClickListener(AgendaWear.this);
        }
    });
}

But unfortunately, I always get the "no data" toast and I'm a bit stuck here, I have the line<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> on both the wear and mobile part of my app, but I don't seem to get any data. Thank you in advance for your help

Expressway answered 20/8, 2014 at 19:42 Comment(0)
G
7

Maybe I can help.

This code works for me, sends an array of strings from the device to be received in the wearable:

Device code:

@Override
public void onCreate() {

    googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(Wearable.API)
            .build();

    googleApiClient.connect();
}    


@Override
public void onConnected(Bundle bundle) {

  String [] myData = new String[]{"data1", "data2", "data3"};
  new DataTask (getActivity(), myData, myListener).execute();
}


class DataTask  extends AsyncTask<Node, Void, Void> {

    private final String[] contents;
    private MyListener myListener;
    Context c;

    public DataTask (Context c, String [] contents, MyListener myListener) {
        this.c = c;
        this.contents = contents;
        this.myListener = myListener;
    }

    @Override
    protected Void doInBackground(Node... nodes) {

        PutDataMapRequest dataMap = PutDataMapRequest.create ("/myapp/myevent");
        dataMap.getDataMap().putStringArray("contents", contents);

        PutDataRequest request = dataMap.asPutDataRequest();

        DataApi.DataItemResult dataItemResult = Wearable.DataApi
                .putDataItem(googleApiClient, request).await();


        Log.d ("[DEBUG] SendDataCoolTask - doInBackground", "/myapp/myevent" status, "+getStatus());
        return null;
    }
}

Wearable code:

@Override
public void onConnected(Bundle bundle) {

    Wearable.DataApi.addListener(googleApiClient, this);
}

    @Override
public void onDataChanged(DataEventBuffer dataEvents) {

    for (DataEvent event: dataEvents) {

        Log.d("[DEBUG] DeviceService - onDataChanged",
                "Event received: " + event.getDataItem().getUri());

        String eventUri = event.getDataItem().getUri().toString();

        if (eventUri.contains ("/myapp/myevent")) {

            DataMapItem dataItem = DataMapItem.fromDataItem (event.getDataItem());
            String[] data = dataItem.getDataMap().getStringArray("contents");

            Log.d("[DEBUG] DeviceService - onDataChanged", "Sending timeline to the listener");

            myListener.onDataReceived(data);
        }
    }
}
Guss answered 21/8, 2014 at 17:59 Comment(6)
Thank you for your answer but there are some things I still don't get, on your device code, what are nodeListener and TIME_LINE_DATA, and how do you call it like when you put your string array in contents ? And on your mobile code, should this be in addconnectioncallback like me ?Expressway
I made a few changes, repect addConnectionCallbaks, my class is implementing that interface, when onConnected is called, at the device the datatTask is called and, at de the wearable the dataListener is suscribedGuss
I still have a few questions, do I have to create a class MyListener ? And what do I have to put in it ? Where do I put this class ? On the wearable or the phone ? how do I initialize it on the wear side ? And you have a symbol called status that is never initialized on the device code, how do you initialize it ? Thank you for your precious help, I think I'm getting closer to itExpressway
I've got it working without MyListener, thank you really for your helpExpressway
I tried everything but can't get this code to work. The mobile client says "D/[DEBUG] SendDataCoolTask - doInBackground﹕ /myapp/myevent statusStatus{statusCode=SUCCESS, resolution=null}", but the wearable device doesn't trigger the onDataChanged. I know I attached the listener for that.Constellation
@Constellation are you sure the GoogleApiClient is connected and you added a listener - during the time you sent it from the mobile. It seems that it does not call onDataChanged() for events sent from mobile when your app is not running and connected and listening. See my answer here: https://mcmap.net/q/1667120/-android-wear-sending-data-to-android-phone-but-phone-appears-to-never-receive-itChitchat

© 2022 - 2024 — McMap. All rights reserved.