pc和android的usb通信

这个在真机上是可以做的

http://www.360doc.com/content/11/0610/17/128678_126054438.shtml

参照这篇文章:有几点注意,按照这么做

主要就是用adb forward重定向端口,将本机地址127.0.0.1的端口重定向

1、有时出现refuse connect (原因不明,重启手机试试)

2、要指定编码

3、adb 的环境变量

4、注意权限

真机做是没问题。。。。

 

服务器-------------------------------------------------------------------------------------------

try {  
            Runtime.getRuntime().exec("cmd /c adb shell am broadcast -a NotifyServiceStop");  
            Runtime.getRuntime().exec("cmd /c adb forward tcp:12580 tcp:10086");  
            Runtime.getRuntime().exec("cmd /c adb shell am broadcast -a NotifyServiceStart");  

           // 不加这个等待,会报connect reset的异常在服务器端         

          Thread.slee(3000);
        } catch (IOException e3) {  
            e3.printStackTrace();  
        }
       
        Socket socket = null;  
        try {  
            System.out.println("TCP 1111" + "C: Connecting...");  
            socket = new Socket("127.0.0.1", 12580);  
            String str = "hi,wufenglong";  
            System.out.println("TCP 221122" + "C:RECEIVE");
            BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
            BufferedInputStream in = new BufferedInputStream(socket  
                    .getInputStream());  
            BufferedReader br = new BufferedReader(new InputStreamReader(  
                    System.in));  
            out.write("测试".getBytes("utf-8"));
            out.flush();
            out.write("测试".getBytes("utf-8"));
            out.flush();
            out.close();
            System.out.println("reader " + br.readLine());
        } catch(Exception e) {
         e.printStackTrace();
        }

android -------------------------------------------------------------------------------------------------

@Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  new Thread() {
   public void run() {
    try {
     ServerSocket server = new ServerSocket(10086);
     Log.d("tag", "server");
     Socket socket = null;
     while((socket = server.accept()) != null) {
      Log.d("tag", "accept");
      InputStream is = socket.getInputStream();
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

      byte[] bytes = new byte[1024];
      int count = is.read(bytes, 0, 1024);
      Log.d("tag", "count " + new String(bytes,0,count,"utf-8"));
     }
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  }.start();
 }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值