android - 如何使用 USB 将消息从 Android 发送到 Windows

标签 android usb serial-communication

我是 Android 的完全菜鸟,仅在按钮激活的基本(1 或 2 行) Activity 级别上,但我想创建一个非常简单的应用程序,当我点击应用程序图标时,它会触发并忘记向我的 Windows 8 PC 上的监听服务器发送消息。电话作为简单的媒体设备连接,没有 Kies,通过 USB 数据线连接。

我可以得到一个消息框说谎并说消息已发送。我需要知道使用哪种通信 channel ,例如一个 COM 端口或什么,以及如何从 Android 通过它发送数据。在 Windows 方面,一旦我确定了如何通信,我就可以帮助自己。

最佳答案

从这个应用程序的桌面端开始: 您可以使用 ADB(Android 调试桥)通过设备和桌面之间的端口建立 tcp/ip 套接字连接。命令是:

adb forward tcp:<port-number> tcp:<port-number>

要在您的 java 程序中运行此命令,您必须创建一个进程构建器,其中此命令在子 shell 上执行。

对于 Windows,您可能需要使用:

process=Runtime.getRuntime().exec("D:\\Android\\adt-bundle-windows-x86_64-20130729\\sdk\\platform-tools\\adb.exe forward tcp:38300 tcp:38300");
        sc = new Scanner(process.getErrorStream());
        if (sc.hasNext()) 
        {
            while (sc.hasNext()) 
                System.out.print(sc.next()+" ");
            System.out.println("\nCannot start the Android debug bridge");
        }
        sc.close();
        }

执行adb命令所需的函数:

String[] commands = new String[]{"/bin/sh","-c", command};
        try {
            Process proc = new ProcessBuilder(commands).start();
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            String s = null;
            while ((s = stdInput.readLine()) != null) 
            {
                sb.append(s);
                sb.append("\n");
            }
            while ((s = stdError.readLine()) != null) 
            {
                sb.append(s);
                sb.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

上述方法会将上述命令作为字符串并在子 shell 上执行

  //Extracting Device Id through ADB
    device_list=CommandExecutor.execute("adb devices").split("\\r?\\n");
    System.out.println(device_list);
    if(device_list.length>1)
    {
        if(device_list[1].matches(".*\\d.*"))
        {
            device_id=device_list[1].split("\\s+");
            device_name=""+CommandExecutor.execute("adb -s "+device_id[0]+" shell getprop ro.product.manufacturer")+CommandExecutor.execute("adb -s "+device_id[0]+" shell getprop ro.product.model");
            device_name=device_name.replaceAll("\\s+"," ");
            System.out.println("\n"+device_name+" : "+device_id[0]);
            device=device_id[0];
            System.out.println("\n"+device);

        }
        else
        {
            System.out.println("Please attach a device");

        }
    }
    else
    {
        System.out.println("Please attach a device");

    }

CommandExecutor 是一个包含 execute 方法的类。 execute 方法的代码与上面发布的代码相同。 这将检查是否有任何设备已连接,如果已连接,它将返回唯一的 ID 号。

最好在执行 adb 命令时使用 id 号码,例如:

adb -s "+device_id[0]+" shell getprop ro.product.manufacturer 

adb -s <put-id-here> shell getprop ro.product.manufacturer

请注意,在 adb 之后必须使用 '-s'。

然后使用 adb forward 命令你需要建立一个 tcp/ip 套接字。这里桌面将是客户端,移动/设备将是服务器。

//Create socket connection
    try{
        socket = new Socket("localhost", 38300);
        System.out.println("Socket Created");
        out = new PrintWriter(socket.getOutputStream(), true);
        out.println("Hey Server!\n");

        new Thread(readFromServer).start();
        Thread closeSocketOnShutdown = new Thread() {
            public void run() {
                try {
                    socket.close();
                } 
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        Runtime.getRuntime().addShutdownHook(closeSocketOnShutdown);
    } 
    catch (UnknownHostException e) {
        System.out.println("Socket connection problem (Unknown host)"+e.getStackTrace());
    } catch (IOException e) {
        System.out.println("Could not initialize I/O on socket "+e.getStackTrace());
    }

然后你需要从服务器读取,即设备:

private Runnable readFromServer = new Runnable() {

    @Override
    public void run() {
try {
            System.out.println("Reading From Server");
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while ((buffer=in.readLine())!=null) {
                System.out.println(buffer);
    }catch (IOException e) {
            try {
                in.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
    }

“缓冲区”将包含设备将从其应用端发送的内容。

现在在您的移动应用程序中,您将需要打开相同的连接并将数据简单地写入缓冲区

public class TcpConnection implements Runnable {

public static final int TIMEOUT=10;
private String connectionStatus=null;
private Handler mHandler;
private ServerSocket server=null; 
private Context context;
private Socket client=null;
private String line="";
BufferedReader socketIn;
PrintWriter socketOut;


public TcpConnection(Context c) {
    // TODO Auto-generated constructor stub
    context=c;
    mHandler=new Handler();
}

@Override
public void run() {
    // TODO Auto-generated method stub


    // initialize server socket
        try {
            server = new ServerSocket(38300);
            server.setSoTimeout(TIMEOUT*1000);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        //attempt to accept a connection
            try{
                client = server.accept();

                socketOut = new PrintWriter(client.getOutputStream(), true);
                socketOut.println("Hey Client!\n");
                socketOut.flush();

                syncContacts();

                Thread readThread = new Thread(readFromClient);
                readThread.setPriority(Thread.MAX_PRIORITY);
                readThread.start();
                Log.e(TAG, "Sent");
            }
            catch (SocketTimeoutException e) {
                // print out TIMEOUT
                connectionStatus="Connection has timed out! Please try again";
                mHandler.post(showConnectionStatus);
                try {
                    server.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            } 
            catch (IOException e) {
                Log.e(TAG, ""+e);
            } 

            if (client!=null) {
                try{
                    // print out success
                    connectionStatus="Connection succesful!";
                    Log.e(TAG, connectionStatus);
                    mHandler.post(showConnectionStatus);
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }

}

private Runnable readFromClient = new Runnable() {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            Log.e(TAG, "Reading from server");
            socketIn=new BufferedReader(new InputStreamReader(client.getInputStream()));
            while ((line = socketIn.readLine()) != null) {
                Log.d("ServerActivity", line);
                //Do something with line
            }
            socketIn.close();
            closeAll();
            Log.e(TAG, "OUT OF WHILE");
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
};

public void closeAll() {
    // TODO Auto-generated method stub
    try {
        Log.e(TAG, "Closing All");
        socketOut.close();
        client.close();
        server.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
} 

private Runnable showConnectionStatus = new Runnable() {
    public void run() {
        try
        {
            Toast.makeText(context, connectionStatus, Toast.LENGTH_SHORT).show();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
};
   }
 }

关于android - 如何使用 USB 将消息从 Android 发送到 Windows,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21748790/

相关文章:

c# - 直接向U盘写入字节

android - linux mint 上 USB 设备的权限 ATTR{idVendor} 使用表 mobii protab2 XXL

c++ - 尝试配置 COM 端口时设置 DCB 失败

android - 从 AutoCompleteTextView 下拉列表中删除阴影

android - libvlc 安卓 : unable to play HTTP network streams

java - 是否可以以编程方式将文件从 Android 智能手机发送到计算机/PC?

无法从 arduino 发送 RS-232 命令

java - 从抽屉导航打开 Activity

java - 从 java 类调用 kotlin 函数会产生错误

c++ - 串行端口接收线程未按预期运行 - C++