PC 客户端与Android 服务端的Socket 同步通信(USB) 收藏 需求: 1.一个android 端的service 后台运行的程序,作为socket 的服务器端;用于接收Pc client端发来的命令,来处理数据后,把结果发给PC client 2.PC 端程序,作为socket 的客户端,用于给android 手机端发操作命令 难点分析: 1.手机一定要有adb 模式,即插上USB 线时马上提示的对话框选adb。好多对手机的操作都可以用adb 直接作。 不过,我发现 LG GW880 就没有,要去下载个 2.android 默认手机端的IP 为“127.0.0.1” 3.要想联通PC 与android 手机的sokcet,一定要用adb forward 来作下端口转发才能连上socket. view plaincopy to clipboardprint? Runtime.getRuntime().exec("adb forward tcp:12580 tcp:10086"); Thread.sleep(3000); Runtime.getRuntime().exec("adb forward tcp:12580 tcp:10086"); Thread.sleep(3000); 4.android 端的service 程序Install 到手机上容易,但是还要有方法来从 PC 的client端来启动手机上的service ,这个办法可以通过 PC 端adb 命令来发一个Broastcast ,手机端再写个接收BroastcastReceive 来接收这个Broastcast,在这个BroastcastReceive 来启动service pc 端命令: view plaincopy to clipboardprint? Runtime.getRuntime().exec( "adb shell am broadcast -a NotifyServiceStart"); Runtime.getRuntime().exec( "adb shell am broadcast -a NotifyServiceStart"); android 端的代码:ServiceBroadcastReceiver.java view plaincopy to clipboardprint? package com.otheri.service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class ServiceBroadcastReceiver extends BroadcastReceiver { private static String START_ACTION = "NotifyServiceStart"; private static String STOP_ACTION = "NotifyServiceStop"; @Override public void onReceive(Context context, Intent intent) { Log.d(androidService.TAG, Thread.currentThread().getName() + "---->" + "ServiceBroadcastReceiver onReceive"); String action = intent.getAction(); if (START_ACTION.equalsIgnoreCase(action)) { cont...