2024年4月20日发(作者:)

PC客户端与Android服务端的Socket同步通信(USB) 收藏

需求:

1.一个android端的service后台运行的程序,作为socket的服务器端;用于接收Pc client

端发来的命令,来处理数据后,把结果发给PC client

端程序,作为socket的客户端,用于给android手机端发操作命令

难点分析:

1.手机一定要有adb模式,即插上USB线时马上提示的对话框选adb。好多对手机的

操作都可以用adb直接作。

不过,我发现LG GW880就没有,要去下载个

d默认手机端的IP为“127.0.0.1”

3.要想联通PC与android手机的sokcet,一定要用adb forward 来作下端口转发才能连

上socket.

view plaincopy to clipboardprint?

time().exec("adb forward tcp:12580 tcp:10086");

(3000);

time().exec("adb forward tcp:12580 tcp:10086");

(3000);

d端的service程序Install到手机上容易,但是还要有方法来从PC的client

端来启动手机上的service ,这个办法可以通过PC端adb命令来发一个Broastcast ,手机

端再写个接收BroastcastReceive来接收这个Broastcast,在这个BroastcastReceive来启动

service

pc端命令:

view plaincopy to clipboardprint?

time().exec(

"adb shell am broadcast -a NotifyServiceStart");

time().exec(

"adb shell am broadcast -a NotifyServiceStart");

android端的代码:

view plaincopy to clipboardprint?

package e;

import astReceiver;

import t;

import ;

import ;

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(, tThread().getName() + "---->"

+ "ServiceBroadcastReceiver onReceive");

String action = ion();

if (START_IgnoreCase(action)) {

ervice(new Intent(context, ));

Log.d(, tThread().getName() + "---->"

+ "ServiceBroadcastReceiver onReceive start end");

} else if (STOP_IgnoreCase(action)) {

rvice(new Intent(context, ));

Log.d(, tThread().getName() + "---->"

+ "ServiceBroadcastReceiver onReceive stop end");

}

}

}

package e;

import astReceiver;

import t;

import ;

import ;

public class ServiceBroadcastReceiver extends BroadcastReceiver {

private static String START_ACTION = "NotifyServiceStart";

@Override

public void onReceive(Context context, Intent intent) {

Log.d(, tThread().getName() + "---->"

private static String STOP_ACTION = "NotifyServiceStop";