简体   繁体   中英

Sending a command to android things from an android device

I am recently working on a project that requires sending a command from my android mobile app to the android things on my raspberry pi 3. How can I achieve this through a WiFi connection?

I only need to send a String to the device.

Using Android Things, you can use the Nearby Messages API, which gives you the ability to communicate to and transfer messages between two Android devices within their apps. Here's a code snippet:

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

If one of your devices isn't connected to internet, you could :

Option 1 : use Google Nearby Connections API , the API choose the best way to communicate (eg: Bluetooth, Wifi...).

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

Option 2 : Use 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 .

If you use system like Raspbian you can transform your Raspberry into a server.Then, You will have different ways to send your command:

Option 1: Set up an Http server on your raspberry (PHP, NodeJS, JEE, ...) and send command via HTTP Request.

Option 2: Set up a Socket Server on your raspberry (Socket.io, raw socket, ...) and send command via socket client

Option 3 Set up MQTT Server on your raspberry and send command via MQTT client (this last option is the way to go when talking about Internet of Things). Note that the program which receive command should implement MQTT Client as MQTT is based on pub/sub pattern.

You can use nanoHttpd on Android things and other library such as retrofit or volley on the Android device.

Check out this example for controlling a car via an Http API: https://github.com/plattysoft/IotCar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM