我正在开发andorid aplication以连接到ELM327用于车载单元的Wifi(我的适配器:http://www.obdinnovations.com/mini-vgate-elm327-wifi-obd2-auto-diagnostics-scanner)。 我应该如何连接到此OBD2适配器然后发送一些信号?
OutputStream outStream = null;
InputStream inStream = null;
Socket socket = null;
InetAddress serverAddr = null;
String serverProtocol = "http";
String serverIpAddress = "192.168.0.10";
public static final int SERVERPORT = 35000;
try {
serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, SERVERPORT);
socket.setKeepAlive(true);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sendDataToOBD(socket1, "ATZ\r");
Log.e("OBD: ATZ", readDataFromOBD(socket));
public void sendDataToOBD(Socket socket1, String paramString) {
try {
outStream = socket1.getOutputStream();
byte[] arrayOfBytes = paramString.getBytes();
outStream.write(arrayOfBytes);
} catch (Exception localIOException1) {
localIOException1.printStackTrace();
}
}
public String readDataFromOBD(Socket socket1) {
while (true) {
try {
inStream = socket1.getInputStream();
String str1 = "";
char c = (char) inStream.read();
str1 = str1 + c;
if (c == '>') {
String datafromOBD = str1.substring(0, -2 + str1.length()).replaceAll(" ", "").trim();
return datafromOBD;
}
} catch (IOException localIOException) {
return localIOException.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
}
我也尝试:
URL url = null;
try {
url = new URL(serverProtocol, serverIpAddress, SERVERPORT, "");
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.connect();
} catch (IOException e) {
e.printStackTrace();
}
方法param是HttpURLConnection连接而不是Socket socket1。
但我无法收到任何信号。我的代码出了什么问题?有什么建议吗?