通过USB编码在Android设备(手机)和PC之间进行通信

时间:2015-12-02 06:14:57

标签: android usb

我搜索了一些网站并了解到通过USB在Android设备(手机)和PC之间进行通信的方式是在手机上实现serversocket的应用程序和在PC上实现客户端套接字的另一个应用程序。我有点修复了手机端的应用程序(现在没有例外),但我得到一个异常“Ljava.lang.StackTraceElement”试图启动一个套接字(“localhost”,38300)。有谁知道这是怎么回事以及如何解决它?我附上了以下代码的两面。

我让它运行的步骤如下

:环境:

三星Android手机,Linux PC,Android Studio开发人员在Linux上运行

:连接步骤

  1. 打开android studio
  2. 在手机上安装一个应用
  3. 在PC机器人模拟器上安装另一个应用程序
  4. 启动手机端应用程序并单击按钮以尝试等待连接 在此步骤中,adb设备将具​​有两个设备
  5. adb -s emulator-5554 -s 1234567890(我的手机)转发tcp:38300 tcp:38300
  6. 启动pc端android模拟器应用程序并单击按钮以启动客户端套接字
  7. 注意:你们都可以看到我可以使用android studio“Android Monitor”窗口查看手机和PC的app shell的日志。

    电话侧

        package com.example.seanhsu.androiddevice_serversocket;
        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import java.io.IOException;
        import java.io.PrintWriter;
        import java.net.ServerSocket;
        import java.net.Socket;
        import java.net.SocketTimeoutException;
        import java.util.Scanner;
    
        import android.app.Activity;
        import android.content.Intent;
        import android.os.Bundle;
        import android.os.Handler;
        import android.util.Log;
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.widget.TextView;
        import android.widget.Toast;
    
        public class AndroidDevice_ServerSocket extends AppCompatActivity implements OnClickListener{
    
        public static final String TAG = "Connection";
        public static final int TIMEOUT = 10;
        Intent i = null;
        TextView tv = null;
        private String connectionStatus = null;
        private String socketData = null;
        private Handler mHandler = null;
        ServerSocket server = null;
    
        String msg;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_android_device__server_socket);
    
        // Set up click listeners for the buttons
        View connectButton = findViewById(R.id.connect_button);
        connectButton.setOnClickListener(this);
        View onBtn = findViewById(R.id.hdmi_on);
        onBtn.setOnClickListener(this);
        View offBtn = findViewById(R.id.hdmi_off);
        offBtn.setOnClickListener(this);
    
        // i = new Intent(this, Connected.class);
        mHandler = new Handler();
        }
    
        public void onClick(View v) {
        switch (v.getId()) {
            case R.id.connect_button:
                tv = (TextView) findViewById(R.id.connection_text);
                // initialize server socket in a new separate thread
                new Thread(initializeConnection).start();
                msg = "Attempting to connect...";
                Log.e(TAG, "1 "+msg);
                Toast.makeText(this, msg, Toast.LENGTH_SHORT/*msg.length()*/).show();
                break;
            case R.id.hdmi_on:
                Log.e(TAG, "disconnect" + Globals.socketOut);
                if (Globals.socketOut != null) {
                    Globals.socketOut.println("hdmiOn");
                    Globals.socketOut.flush();
                    msg = "disconnect hdmi on";
                    Log.e(TAG, "2 "+msg);
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT/*msg.length()*/).show();
                }
                else
                {
                    msg = "disconnect hdmi on is null";
                    Log.e(TAG, "3 "+msg);
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT/*msg.length()*/).show();
                }
                break;
            case R.id.hdmi_off:
                Log.e(TAG, "disconnect" + Globals.socketOut);
                if (Globals.socketOut != null) {
                    Globals.socketOut.println("hdmiOff!!");
                    Globals.socketOut.flush();
                    msg = "disconnect hdmi off";
                    Log.e(TAG, "4 "+msg);
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT/*msg.length()*/).show();
                }
                else
                {
                    msg = "disconnect hdmi off is null";
                    Log.e(TAG, "5 "+msg);
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT/*msg.length()*/).show();
                }
                break;
            }
        }
    
        private Runnable initializeConnection = new Thread() {
        public void run() {
    
            Socket client = null;
            // initialize server socket
            try {
                server = new ServerSocket(38300);
                server.setSoTimeout(TIMEOUT * 5000);
    
                // attempt to accept a connection
                client = server.accept();
                Globals.socketIn = new Scanner(client.getInputStream());
                Globals.socketOut = new PrintWriter(client.getOutputStream(),
                        true);
    
                // Globals.socketIn.
            } catch (SocketTimeoutException e) {
                // print out TIMEOUT
                Log.e(TAG, "aaa=== " + e);
                msg = "Connection has timed out! Please try again";
                Log.e(TAG, "6 "+msg);
                //Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();//method error, this causes program terminated
                mHandler.post(showConnectionStatus);
            } catch (IOException e) {
                Log.e(TAG, "bbb=== " + e);
                msg = "IO Exception";
                Log.e(TAG, "7 "+msg);
                //Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();//method error, this causes program terminated
            } finally {
                // close the server socket
                try {
                    if (server != null)
                        server.close();
                } catch (IOException ec) {
                    Log.e(TAG, "ccc=== " + ec);
                    Log.e(TAG, "Cannot close server socket" + ec);
                    msg = "Cannot close server socket";
                    Log.e(TAG, "8 "+msg);
                    //Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();//method error, this causes program terminated
                }
            }
    
            if (client != null) {
                Globals.connected = true;
                // print out success
                connectionStatus = "Connection was succesful!";
                Log.e(TAG, "9 "+connectionStatus);
                mHandler.post(showConnectionStatus);
                while (Globals.socketIn.hasNext()) {
                    socketData = Globals.socketIn.next();
                    mHandler.post(socketStatus);
    
                }
                // startActivity(i);
            }
        }
    };
        /**
        * Pops up a "toast" to indicate the connection status
        */
        private Runnable showConnectionStatus = new Runnable() {
        public void run() {
            Log.e(TAG, "10 "+connectionStatus);
            Toast.makeText(getBaseContext(), connectionStatus,
                    Toast.LENGTH_SHORT).show();
        }
        };
    
        private Runnable socketStatus = new Runnable() {
    
        public void run() {
            TextView tv = (TextView) findViewById(R.id.connection_text);
            tv.setText(socketData);
        }
        };
    
        public static class Globals {
        public static boolean connected;
        public static Scanner socketIn;
        public static PrintWriter socketOut;
        }
        }
    

    PC端

        package com.example.seanhsu.pchost_clientsocket_withactivity;
        import android.support.v7.app.AppCompatActivity;
        import java.io.DataOutputStream;
        import java.io.IOException;
        import java.io.PrintWriter;
        import java.net.ServerSocket;
        import java.net.Socket;
        import java.net.SocketTimeoutException;
        import java.net.UnknownHostException;
        import java.util.Scanner;
        import android.app.Activity;
        import android.content.Intent;
        import android.os.Bundle;
        import android.os.Handler;
        import android.util.Log;
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.widget.TextView;
        import android.widget.Toast;
    
        public class PCHost_ClientSocket_with_Activity extends AppCompatActivity implements OnClickListener{
    
        Socket socket;
        PrintWriter out;
        Scanner sc;
        String msg;
    
        private String TAG = "PCHost_ClientSocket_withActivity";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pchost__client_socket_with_);
        View connectButton = findViewById(R.id.connect_button);
        connectButton.setOnClickListener(this);
    
        //when the emulator start running, it's already in the emulator shell, so it cann't execute adb command
        //execAdb();
        }
        public void onClick(View v) {
        //cannot run on main thread
        //need to run on another thread, otherwise it will get android.os.NetworkOnMainThreadException exception
        new Thread(initializeConnection).start();
        //initializeConnection();
    
        /*while(sc.hasNext()) {
            System.out.println(System.currentTimeMillis() + " / " + sc.nextLine());
            Log.e(TAG, "12 "+System.currentTimeMillis() + " / " + sc.nextLine());
        }*/
        }
        //cannot run on main thread
        //need to run on another thread, otherwise it will get android.os.NetworkOnMainThreadException exception
        private Runnable initializeConnection = new Thread() {
        public void run() {
            msg = "initializeConnection";
            Log.e(TAG, msg);
    
            //Create socket connection
            try{
                Log.e(TAG, "============0============");
                socket = new Socket("localhost", 38300);
                Log.e(TAG, "============1============");
                out = new PrintWriter(socket.getOutputStream(), true);
                Log.e(TAG, "============2============");
                //in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                sc=new Scanner(socket.getInputStream());
                Log.e(TAG, "============3============");
                // add a shutdown hook to close the socket if system crashes or exists unexpectedly
                Thread closeSocketOnShutdown = new Thread() {
                    public void run() {
                        try {
                            Log.e(TAG, "============4============");
                            socket.close();
                            msg = "closeSocketOnShutdown socket close";
                            Log.e(TAG, msg);
                            Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();
                        } catch (IOException e) {
                            Log.e(TAG, "============5============");
                            e.printStackTrace();
                            msg = "closeSocketOnShutdown IOException";
                            Log.e(TAG, msg);
                            Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();
                        }
                    }
                };
                Log.e(TAG, "============6============");
                Runtime.getRuntime().addShutdownHook(closeSocketOnShutdown);
                Log.e(TAG, "============7============");
            } catch (UnknownHostException e) {
                //Print.fatalError(“Socket connection problem (Unknown host)”+e.getStackTrace());
                msg = "Socket connection problem (Unknown host)"+e.getStackTrace();
                Log.e(TAG, msg);
                Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                //Print.fatalError(“Could not initialize I/O on socket “+e.getStackTrace());
                msg = "Could not initialize I/O on socket "+e.getStackTrace();
                Log.e(TAG, msg);
                Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();
            }
        }
    };
    }
    

    我一直异常:

      

    无法初始化套接字上的I / O [Ljava.lang.StackTraceElement; @ 14710f5

    最初我在手机端应用程序上也有IO异常,但我在清单中添加了<uses-permission android:name="android.permission.INTERNET"/>,现在没关系。因此,我还在PC端应用程序的清单中添加<uses-permission android:name="android.permission.INTERNET"/>,但仍无法解决此问题。

0 个答案:

没有答案