从可穿戴设备发送消息到手机然后立即回复 [英] Send message from wearable to phone and then immediately reply

查看:97
本文介绍了从可穿戴设备发送消息到手机然后立即回复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天一整天都在与Android Wear Message API作斗争,并且终于接受了我需要一些帮助。

I've been battling with the Android Wear Message API all day today and have finally accepted I need some help with this.

我的应用程序非常简单。 Mobile部分包含一个MainActivity(除了显示Hello world和一个扩展 WearableListenerService 的Service之外什么都没有.Mush部分只是一个带有单个Button的MainActivity,并实现了 MessageApi。 MessageListener

My app is very straightforward. The Mobile portion consists of a MainActivity (which does nothing but display "Hello world" and a Service which extends WearableListenerService. The Wear portion is just a MainActivity with a single Button, and implements MessageApi.MessageListener.

想法很简单:按Wear设备上的按钮向移动设备发送消息。当移动设备收到消息时,显示消息发件人的消息路径(例如 / mobile )的Toast。执行此操作后,移动设备应立即发送消息 返回 使用我的 reply()方法连接到Wear设备。我想要做的就是记录此消息。

The idea is simple: press the Button on the Wear device which sends a message to the Mobile. When the Mobile receives the message, it displays a Toast with the sender's message path (e.g. /mobile). Immediately after doing this, the Mobile should send a message back to the Wear device using my reply() method. All I want to do then is Log this message.

我可以实现第一部分完全没问题。当按下按钮时,手机会弹出一个叫/ mobile的Toast。然而,回复似乎只是在以太中丢失;没有错误,但也没有消息。

I can achieve the first part perfectly fine. When the Button is pressed, the Mobile pops up a Toast saying "/mobile". The reply, however, seems to just get lost in the aether; no errors, but no message either.

有人可以帮助我了解我做错了什么?我已粘贴下面的文件。

Can someone please help me understand what I'm doing wrong? I have pasted my files below.

这个是我关注的教程。干杯!

This is the tutorial I am following. Cheers!

package org.thecosmicfrog.toastdroidmessageapitutorial;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.wearable.view.WatchViewStub;
import android.util.Log;
import android.view.View;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class MainActivity extends Activity implements MessageApi.MessageListener {

    private final String LOG_TAG = MainActivity.class.getSimpleName();

    private static final long CONNECTION_TIME_OUT_MS = 100;
    private static final String MOBILE_PATH = "/mobile";

    private GoogleApiClient googleApiClient;
    private String nodeId;

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

        initGoogleApiClient();

        final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
        stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
            @Override
            public void onLayoutInflated(WatchViewStub stub) {
                initWidgets();
            }
        });
    }

    private void initGoogleApiClient() {
        googleApiClient = getGoogleApiClient(this);
        retrieveDeviceNode();
    }

    private GoogleApiClient getGoogleApiClient(Context context) {
        return new GoogleApiClient.Builder(context)
                .addApi(Wearable.API)
                .build();
    }

    private void retrieveDeviceNode() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (googleApiClient != null && !(googleApiClient.isConnected() || googleApiClient.isConnecting()))
                    googleApiClient.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);

                NodeApi.GetConnectedNodesResult result =
                        Wearable.NodeApi.getConnectedNodes(googleApiClient).await();

                List<Node> nodes = result.getNodes();

                if (nodes.size() > 0)
                    nodeId = nodes.get(0).getId();

                Log.v(LOG_TAG, "Node ID of phone: " + nodeId);

                googleApiClient.disconnect();
            }
        }).start();
    }

    private void initWidgets() {
        findViewById(R.id.button_toast).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendToast();
            }
        });
    }

    private void sendToast() {
        if (nodeId != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (googleApiClient != null && !(googleApiClient.isConnected() || googleApiClient.isConnecting()))
                        googleApiClient.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);

                    Wearable.MessageApi.sendMessage(googleApiClient, nodeId, MOBILE_PATH, null).await();
                    googleApiClient.disconnect();
                }
            }).start();
        }
    }

    @Override
    public void onMessageReceived(MessageEvent messageEvent) {
        Log.v(LOG_TAG, "In onMessageReceived()");

        if (messageEvent.getPath().equals("/wear")) {
            Log.v(LOG_TAG, "Success!");
        }
    }
}



手机:ListenerService.java



Mobile: ListenerService.java

package org.thecosmicfrog.toastdroidmessageapitutorial;

import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.Wearable;
import com.google.android.gms.wearable.WearableListenerService;

import java.util.concurrent.TimeUnit;

public class ListenerService extends WearableListenerService {

    private final String LOG_TAG = ListenerService.class.getSimpleName();

    private static GoogleApiClient googleApiClient;

    private static final long CONNECTION_TIME_OUT_MS = 100;
    private static final String WEAR_PATH = "/wear";
    private String nodeId;

    @Override
    public void onMessageReceived(MessageEvent messageEvent) {
        if (messageEvent.getPath().equals("/mobile")) {
            nodeId = messageEvent.getSourceNodeId();
            Log.v(LOG_TAG, "Node ID of watch: " + nodeId);
            showToast(messageEvent.getPath());

            reply(WEAR_PATH);
        }
    }

    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    private void reply(final String path) {
        googleApiClient = new GoogleApiClient.Builder(getApplicationContext())
                .addApi(Wearable.API)
                .build();

        Log.v(LOG_TAG, "In reply()");
        Log.v(LOG_TAG, "Path: " + path);

        if (googleApiClient != null && !(googleApiClient.isConnected() || googleApiClient.isConnecting()))
            googleApiClient.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);

        Wearable.MessageApi.sendMessage(googleApiClient, nodeId, path, null).await();
        googleApiClient.disconnect();
    }
}

Mobile MainActivity非常简单,所以我离开了为了清楚起见。

The Mobile MainActivity is pretty trivial so I've left it out for clarity.

推荐答案

你永远不会打电话给 MessageApi.addListener(),因此永远不会注册 MessageListener 来接收消息。您还应该拨打 MessageApi.removeListener()

You never call MessageApi.addListener() in your Wear activity so your MessageListener is never registered to receive messages. You should also call MessageApi.removeListener() when your activity is being destroyed.

注意:两种方法都需要连接 GoogleApiClient 。如果您在活动期间打开 GoogleApiClient 而不是尝试连接/ removeListener() /断开 onDestroy()

Note: both methods require a connected GoogleApiClient. It may make logic easier if you leave a GoogleApiClient open throughout the duration of your activity rather than try connecting/removeListener()/disconnect in your onDestroy().

这篇关于从可穿戴设备发送消息到手机然后立即回复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆