手机与pc USB连接adb socket通信

时间:2022-12-05 17:35:57

手机通过usb线连接pc,实现pc主动向手机发送消息;

 

一、获取与电脑连接的所有手机

 

public static List<Device> findDevices(){
List<Device>devices = new ArrayList<Device>();
String str = null;
int port = 15000;
Process process = null;
Device device = null;
String[] deviceStr = new String[2];
List<String>lines=new ArrayList<String>();
try {
process = Runtime.getRuntime().exec("adb devices");
InputStream in = process.getInputStream();
BufferedReader read=new BufferedReader(new InputStreamReader(in));

while ((str=read.readLine())!=null){
lines.add(str);
System.out.println(str);
}
for(int i=1;i<lines.size()-1;i++){
str = lines.get(i);
deviceStr = str.split("");
if ("device".equals(deviceStr[1])) {
device = new Device();
device.setDeviceId(deviceStr[0]);
device.setState(deviceStr[1]);
// 目前先指定port;
device.setPort(port);
port++;
devices.add(device);
}
}
} catch (IOException e) {
e.printStackTrace();
}

return devices;
}


二、端口映射;启动手机端的app

 

public static void portForwardBydevice(Devices device){
String a = null;
String b = null;
String c = null;
String d = null;
Log logger = LogFactory.getLog(DeviceFinder.class);

a = "adb -s " + device.getDeviceId()+ " shell am broadcast -a NotifyServiceStop";
b = "adb -s " + device.getDeviceId() + " forward tcp:"+device.getPort()+" tcp:12222";
c = "adb -s " + device.getDeviceId()+ " shell am broadcast -a NotifyServiceStart";
d= "adb -s " + device.getDeviceId()+ " shell am start -n com.newland.realmobiledetection/com.newland.realmobiledetection.system.activity.WelcomeActivity";
logger.error("......device...a.."+a);
logger.error("......device...b.."+b);
logger.error("......device...c.."+c);
logger.error("......device...d.."+d);
try {
Runtime.getRuntime().exec(d);
Thread.sleep(1000);
Runtime.getRuntime().exec(a);
Thread.sleep(1000);
Runtime.getRuntime().exec(b);
Thread.sleep(1000);
Runtime.getRuntime().exec(c);
Thread.sleep(1000);
logger.error("端口映射完成。。");
} catch (IOException e) {

logger.error("与手机通信异常"+e.getMessage());
}catch (InterruptedException e) {
logger.error("线程中断异常"+e.getMessage());
}

}

 

三、连接:

 

try {  
InetAddress serverAddr = null;
serverAddr = InetAddress.getByName("127.0.0.1");
socket = new Socket(serverAddr, pcPort);
socket.setKeepAlive(true);
socket.setSoTimeout(120 * 1000);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
out.write(requestContent.getBytes());
out.flush();
responseContent=readFromSocket(in);
System.out.println(":::::::::::::receive::::::::::::" + responseContent);
logger.info(":::::::::::::receive::::::::::::" +responseContent);
obj = gson.fromJson(responseContent, method.getGenericReturnType());


手机端app);
serverSocket =new ServerScoket(12222);

Socket socket = serverSocket.accept();

out = new BufferedOutputStream(socket.getOutputStream());
in = new BufferedInputStream(socket.getInputStream());