您好,我有一个用 Java 编写的代码,我需要在 android studio 中创建一个与 GPS 设备的 TCP 连接,您可以在其中输入 IP/PORT 地址,如果有人可以帮助我,请提前致谢。public class TCPConnection implements Runnable {/** * <h1>TCP Connection construct</h1> * <p>The tcp connection requires two parameters socket and view model. </p> * @param socket to establish connection. * */TCPConnection(Socket socket) { super(); this.socket = socket; converter = new Converter(); crc16 = new Crc16();}/** * <h1>Run function to start listener</h1> * <p>Simply runs the runnable thread to listen everything from client</p> * */public void run() { try { inputStream = new DataInputStream(socket.getInputStream()); outputStream = new DataOutputStream(socket.getOutputStream()); Listen(); } catch (IOException e) { e.printStackTrace(); }}可能我需要创建一个按钮来开始监听传入连接,也使用 Log 类..... /** * <h1>Listen</h1> * <p>Function for listening connected client</p> * @throws IOException throws exception if input stream is interrupted * */private void Listen() throws IOException { while (flag) { System.out.println("listening..."); while (!socket.isClosed() && inputStream.available() == 0) { try { Thread.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } Communicate(); } inputStream.close(); outputStream.close(); socket.close();}/** * <h1>Get Number Of Records</h1> * <p>Reads the number of records to send back to the sender</p> * @param data the parameter is a received hex data * @return String format number of records * */private String GetNumberOfRecords(String data) { return data.substring(18, 20);}
1 回答
侃侃尔雅
TA贡献1801条经验 获得超16个赞
只要您的 android API 级别支持您使用的 Java 版本,Android 就支持 Java 代码。没有任何理由不能在 Android 中使用它。
请注意,如果您在 UI 线程上运行任何网络任务,Android 将抛出异常。例如,创建套接字应该作为 IntentService 或 AsyncTask 运行,还有其他选项。
添加回答
举报
0/150
提交
取消