如何使用USB从Android向Windows发送消息

Pro*_*ofK 12 usb android serial-communication

我是Android上的一个完整的菜鸟,只是在按钮激活的基本(1或2行)活动的水平上,但我想创建一个非常简单的应用程序,当我点击应用程序图标时,它会触发并忘记消息到我的Windows 8 PC上的监听服务器.手机通过USB线连接为简单的媒体设备,无需Kies.

我可以得到一个消息框,并说消息已发送.我需要知道要使用哪种通信通道,例如COM端口或什么,以及如何通过Android发送数据.在Windows方面,一旦我建立了沟通方式,我就能帮助自己.

AB *_* DC 16

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

adb forward tcp:<port-number> tcp:<port-number>
Run Code Online (Sandbox Code Playgroud)

要在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();
        }
Run Code Online (Sandbox Code Playgroud)

执行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();
        }
Run Code Online (Sandbox Code Playgroud)

上面的方法将上述命令作为字符串并在子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");

    }
Run Code Online (Sandbox Code Playgroud)

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

执行adb命令时最好使用id号:

adb -s "+device_id[0]+" shell getprop ro.product.manufacturer 
Run Code Online (Sandbox Code Playgroud)

要么

adb -s <put-id-here> shell getprop ro.product.manufacturer
Run Code Online (Sandbox Code Playgroud)

注意'-s'是adb之后的必需品.

然后使用adb forward commnd你需要建立一个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());
    }
Run Code Online (Sandbox Code Playgroud)

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

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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

'缓冲区'将包含设备将从应用程序末尾发送的内容.

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

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();
        }
    }
};
   }
 }
Run Code Online (Sandbox Code Playgroud)