Two androids communicate via usb

need:

Now there are two devices, both running android system, how to communicate via usb?

Prepare knowledge:

  1. Two devices connected through usb are divided into primary and secondary, one is the master device and the other is the slave device.
  2. The usb port used to debug android is called otg port. There are two uses for this mouth. When the otg of android is connected to a computer and other devices, the computer supplies power to the android, the computer is the master device (called the host), and the android is the slave device. When the otg of android is connected to a device such as a u disk, android supplies power to the u disk, android is the host and the u disk is the slave device.
  3. Of course, android can also have a usb port dedicated to the host.
  4. Android also comes with adb debugging tools, located in the /system/bin directory.
  5. If you use android as the host's usb port and connect it to the otg port of another android, then this android can run the built-in adb tool to debug another android. But the android running adb must be rooted.

accomplish:

When two androids need to communicate through usb, you can use one android as the host's usb port, connect to the other android's otg port, and then use adb to send commands to the other android. adb has a wealth of commands that can send broadcasts, copy files to each other, and so on.

It is also possible to run adb commands in java code.

public static String execRootCmd(String cmd) {
			String result = "";
			DataOutputStream dos = null;
			DataInputStream dis = null;

			try {
				Process p = Runtime.getRuntime().exec("su");
				dos = new DataOutputStream(p.getOutputStream());
				dis = new DataInputStream(p.getInputStream());

				Log.i(TAG, cmd);
				dos.writeBytes(cmd + "\n");
				dos.flush();
				dos.writeBytes("exit\n");
				dos.flush();
				String line = null;
				while ((line = dis.readLine()) != null) {
					Log.d("result", line);
					result += line;
				}
				p.waitFor();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (dos != null) {
					try {
						dos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (dis != null) {
					try {
						dis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return result;
		}

For example, the following command plays a video:

/system/bin/adb shell am start -a android.intent.action.VIEW -d "file:///mnt/sdcard/Download/ddnf.mp4" -t "video/*"

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325363285&siteId=291194637