I use a Thread Runnable or an Intent Service?


when we use for example

new Thread(new Runnable() {
                public void run() {
                try {
                    DatagramSocket clientsocket= new DatagramSocket(5005);
                    byte[] receivedata = new byte[30];
                    while(true) {
                        DatagramPacket recv_packet = new DatagramPacket(receivedata, receivedata.length);
                        Log.d("UDP", "S: Receiving...");
                        String receivedstring = new String(recv_packet.getData());
                        Log.d("UDP", " Received String: " + receivedstring);
                        InetAddress ipaddress = recv_packet.getAddress();
                        int port = recv_packet.getPort();
                        Log.d("UDP", "IPAddress : " + ipaddress.toString());
                        Log.d("UDP", "Port : " + Integer.toString(port));
                } catch (SocketException e) {
                    Log.e("UDP", "Socket Error", e);
                } catch (IOException e) {
                    Log.e("UDP", "IO Error", e);

Are we generating an independent thread to the activity that will continue executing the run() until we close the APP or stop it in some way? And if so. Can we interact with the interface from this thread? I currently use an Intent Service but maybe this option is more appropriate.

asked by wasous 12.06.2017 в 19:04

2 answers


What do you need to do? the intent are services that belong to the main thread of the app but run independently of the "graphical interface" or activity, that is, if you start a service and put a task in that service it continues executing it even when you "minimize" the application (to unless the activity that calls it is destroyed ... what stops the service)
Stop by here I think it will serve you link

answered by 12.06.2017 в 20:11

Can we interact with the interface from this thread?

You will probably have the error NetworkOnMainThread as you are performing operations that modify the UI, in the main thread.

I recommend using runOnUiThread ()

    runOnUiThread(new Runnable() {
        public void run() {
            try {  

               //Realizar aquí tu proceso!                    

            } catch (Exception e) {
                Log.e("Error", "Exception: " + e.getMessage());

Another option is to use Asynctask

or Handler.post () .

answered by 12.06.2017 в 22:54