Question

Hi !!

I try to build an Android Application to control the Ar drone. But i have a problem when i try to connect my device with the drone. I created a Thread to do a socket. But when i run it in the main activity i have a exception : android.os.NetworkOnMainThreadException .

This is my code with my Thread in ThreadCmd class:

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;
            }

After in the main activity :

 Threadcmd tc = new Threadcmd();
 tc.run(); 

I dont see my error so i ask to you if you can help me !! ( i don't forget the permission)

ps: please excuse my english :)

Was it helpful?

Solution

tc.run(); 

This is your problem. Here you call the run() method on the same thread.

In order to actually start a new thread, call tc.start();

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top