从 android 台设备向 android 事物发送命令

Sending a command to android things from an android device

我最近在做一个项目,需要从我的 android 移动应用程序向我的 raspberry pi 上的 android 东西发送命令 3. 我如何通过WiFi 连接?

我只需要向设备发送一个字符串。

如果你使用像 Raspbian 这样的系统,你可以将你的 Raspberry 变成 server.Then,你将有不同的方式来发送你的命令:

选项 1: 在您的树莓派上设置一个 Http 服务器(PHP、NodeJS、JEE,...)并通过 HTTP 请求发送命令。

选项 2: 在你的树莓派上设置套接字服务器(Socket.io,原始套接字,...)并通过套接字客户端发送命令

选项 3 在您的树莓派上设置 MQTT 服务器并通过 MQTT 客户端发送命令(最后一个选项是谈论物联网的方式)。请注意,接收命令的程序应实现 MQTT 客户端,因为 MQTT 基于 pub/sub 模式。

使用 Android 事物,您可以使用 Nearby Messages API,这使您能够在两个 Android 设备的应用程序中进行通信和传输消息.这是一个代码片段:

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  ...
  mMessageListener = new MessageListener() {
    @Override
    public void onFound(Message message) {
        Log.d(TAG, "Found message: " + new String(message.getContent()));
    }

    @Override
    public void onLost(Message message) {
        Log.d(TAG, "Lost sight of message: " + new String(message.getContent()));
    }
  }

  mMessage = new Message("Hello World".getBytes());
}

@Override
public void onStart() {
  super.onStart();
  ...
  Nearby.getMessagesClient(this).publish(mMessage);
  Nearby.getMessagesClient(this).subscribe(mMessageListener);
}

@Override
public void onStop() {
  Nearby.getMessagesClient(this).unpublish(mMessage);
  Nearby.getMessagesClient(this).unsubscribe(mMessageListener);
  ...
  super.onStop();
}

您可以在 Android 设备上使用 nanoHttpd,并在 Android 设备上使用其他库,例如 retrofit 或 volley。

查看这个通过 Http 控制汽车的示例 API:https://github.com/plattysoft/IotCar

如果您的其中一台设备未连接到互联网,您可以:

选项 1: 使用 Google Nearby Connections API ,API 选择最佳的通信方式(例如:蓝牙、Wifi...)。

https://github.com/googlesamples/android-nearby/tree/master/connections

选项 2: 使用 Socket to communicate but your devices need to be on the same network. If they aren't connected to the same network, you can connect them using WIFI P2P.