你好 !!
我尝试构建一个 Android 应用程序来控制 Ar 无人机。但是当我尝试将我的设备与无人机连接时遇到问题。我创建了一个线程来做一个套接字。但是当我在主要活动中运行它时,我遇到了一个异常: android.os.NetworkOnMainThreadException。
这是我在 ThreadCmd 类中的线程代码:
String commande="";
byte[] cmdToByte;
String iPinString;
InetAddress IpDrone;
DatagramSocket clientSocket;
Thread threadDecollage;
TextView tv ;
boolean etat;
DatagramPacket sendPacketWithCmd;
private byte[] ip = {(byte)192, (byte)168, (byte)1, (byte)1 };
boolean isRunning = true;
private final static long TIME_SLEEP= 20;
public void run() {
try {
IpDrone = InetAddress.getByAddress(ip);
} catch (UnknownHostException e1) {
e1.printStackTrace();
etat = false;
}
try {
clientSocket = new DatagramSocket();
} catch (SocketException e) {
e.printStackTrace();
etat = false;
}
while(isRunning){
runControl();
try {
Thread.sleep(TIME_SLEEP);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void runControl(){
commande ="AT*REF=1,290717696<LF>AT*REF=2,290717952<LF>AT*REF=3,290717696<LF>";
cmdToByte = commande.getBytes();
try {
sendPacketWithCmd = new DatagramPacket(cmdToByte,cmdToByte.length,IpDrone,5556);
clientSocket.send(sendPacketWithCmd);
} catch (IOException e) {
e.printStackTrace();
etat = false;
}
etat = true;
isRunning=false;
}
public boolean retourneetat(){
return etat;
}
在主要活动之后:
Threadcmd tc = new Threadcmd();
tc.run();
我没有看到我的错误,所以我问你是否可以帮助我!(我没有忘记许可)
ps:请原谅我的英语:)