从可穿戴设备发送信息到手机并立即回复。

11
我今天一整天都在与Android Wear Message API作斗争,最终认识到我需要一些帮助。
我的应用程序非常简单。移动端由一个MainActivity(仅显示“Hello world”)和一个继承WearableListenerService的Service组成。手表端只有一个带有单个按钮的MainActivity,并实现MessageApi.MessageListener。
想法很简单:按下手表设备上的按钮,向移动端发送消息。当移动端接收到消息时,它将显示一个Toast,其中包含发送者的消息路径(例如/mobile)。在此之后,移动端应使用我的reply()方法向手表设备发送一条消息。然后我只想记录这条消息。
我可以完美地完成第一部分。当按钮被按下时,移动端会弹出一个Toast,显示“/mobile”。然而,回复似乎就消失在了虚空中;没有错误,但也没有消息。
请问有谁能帮我理解我做错了什么吗?我已经在下面粘贴了我的文件。

是我正在跟随的教程。干杯!

穿戴:MainActivity.java

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

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();
    }
}

移动 MainActivity 非常简单,为了清晰起见,我将其省略了。
1个回答

5

你在 Wear 活动中从未调用 MessageApi.addListener(),因此你的 MessageListener 从未注册以接收消息。当活动被销毁时,你还应该调用 MessageApi.removeListener()

注意:这两种方法都需要连接到一个已连接的 GoogleApiClient。如果你在 onDestroy() 中尝试连接/removeListener()/断开连接,它可能会使逻辑更加复杂,因此最好在整个活动期间保持一个打开的 GoogleApiClient


啊,太棒了,谢谢你ianhanniballake!第一个问题应该对我来说很明显,但是你的第二点真的帮了我很多。我没有意识到只有在GoogleApiClient连接时才能添加侦听器。断开(disconnect())方法确实导致侦听器永远不会被添加。现在看起来一切都按预期工作了。再次感谢! - Aaron Hastings

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接