Lissiel
Lissiel

Reputation: 13

Update android UI from do in background task

I am using AsyncTask to do a background task. The task is in a while loop. How can I update my UI as on post execute dose not work if the background task is still running.

Thanks

protected String doInBackground(Void... params) {

        while(true){


        Log.i(LOG_TAG, "Executing Background Task");
        try{


            String dataFromBT = btc.getData();
            Log.i(LOG_TAG, "BT Data: "+dataFromBT);
             if(dataFromBT.contains("B1")){
                 dataFromBT = "Warning Message 1";

             }
             if(dataFromBT.contains("B2"))
             {
                 dataFromBT="Warning Message 2";
             }

             if(dataFromBT.contains("B3")){

                 dataFromBT="Warning Message 3";
             }

             if(dataFromBT.contains("B4")){

                 dataFromBT="Warning Message 4";
             }

            if (groupOwnerAddress!=null) {


                Log.i(LOG_TAG, "Info is not null mobiles connected");



                // This is the server side 
                if (isthisthegrpowner == true) {

                    Log.w(LOG_TAG, "Group Owner: I am the Group Owner ");

                    Log.w(LOG_TAG, "Group Owner: Opening a Server Socket");
                    ServerSocket serverSocket;  
                    serverSocket = new ServerSocket(8988);
                    Log.w(LOG_TAG, "Group Owner: Server Socket Opened, waiting for PEER");

                    Socket client = serverSocket.accept();
                    Log.w(LOG_TAG, "Group Owner: Server Connection Done");
                    serverSocket.setReuseAddress(true); 

                    try{

                            // Get client IP from Socket
                            clientipadd = client.getRemoteSocketAddress();
                            clientport = client.getPort();
                            String clientip = clientipadd.toString();
                            Log.w(LOG_TAG, "Group Owner: Client IP from socket found: " + clientip);


                            Log.w(LOG_TAG, "Group Owner: Input Stream Started");
                            InputStream inputstream = client.getInputStream();
                            ByteArrayOutputStream byteArrayOutputStream = 
                                    new ByteArrayOutputStream(1024);
                            byte[] buffer = new byte[1024];

                            String response = "";

                            int bytesRead;
                             while ((bytesRead = inputstream.read(buffer)) != -1){
                                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                                    response += byteArrayOutputStream.toString("UTF-8");
                             }


                             // Split the string sent from the client and add it to the HashMap 
                             String input = response;
                             final String[] splitStringArray = input.split(" ");
                             String a = splitStringArray[0];
                             String b = splitStringArray[1];
                             String c = splitStringArray[2];
                             String d = splitStringArray[3];
                             String e = splitStringArray[4];
                             Log.w(LOG_TAG, "Group Owner: Response from client split: "  + " 1: " + a + " 2: "+ b + " 3:" + c + " 4: " + d + " 5: " + e );

                             data.put(clientip, new VehicleInfoEntry(a, b , c));    
                             client.shutdownInput();


                             Log.w(LOG_TAG, "Group Owner: Reply from Peer: " + response);

                    }finally{

                        Log.w(LOG_TAG, "Group Owner: Output Stream started");
                        OutputStream stream = client.getOutputStream();
                        PrintStream printStream = new PrintStream(stream); 
                        printStream.print("hello hellomac hellodata" + Latitude + "  " + Longitude + dataFromBT);
                        Log.w(LOG_TAG, "Group Owner: Output Stream finished");

                        serverSocket.close();
                        Log.w(LOG_TAG, "Group Owner: Socket Closed");
                    }

                    // This is the client side
                    } else{

                    Log.w(LOG_TAG, "PEER: I am a PEER");
                    InetAddress ownerAdd = groupOwnerAddress;
                    int ownerPort = 8988;
                    Socket server = new Socket(); 
                    try {


                        server.connect((new InetSocketAddress(ownerAdd, ownerPort)));
                        Log.w(LOG_TAG, "PEER: Socket done ");

                        Log.w(LOG_TAG, "PEER: Output Stream Started ");
                        OutputStream stream = server.getOutputStream();
                        PrintStream printStream = new PrintStream(stream); 
                        printStream.print("hello hellomac hellodata" + " " + Latitude + " " + Longitude + dataFromBT);

                        Log.w(LOG_TAG, "PEER: Output Stream Done");

                        server.shutdownOutput();
                       // printStream.close();
                    } finally {

                        Log.w(LOG_TAG, "PEER: Input Stream Started");

                        InputStream inputstream = server.getInputStream();
                        ByteArrayOutputStream byteArrayOutputStream = 
                                new ByteArrayOutputStream(1024);
                        byte[] buffer = new byte[1024];

                        String response = "";

                        int bytesRead;
                         while ((bytesRead = inputstream.read(buffer)) != -1){
                                byteArrayOutputStream.write(buffer, 0, bytesRead);
                                response += byteArrayOutputStream.toString("UTF-8");

                                Log.w(LOG_TAG, "PEER: Reply from Group Owner:  " + response);

                                server.close();
                                Log.w(LOG_TAG, "PEER: Server socket closed");

                         }

                    }

                    }
                }

                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }finally {


                }try {

                    Thread.sleep(2000); // changed to 5000 for other peer
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } 





            }



    }

Upvotes: 0

Views: 628

Answers (2)

Bojan Kseneman
Bojan Kseneman

Reputation: 15668

Use the publishProgress method. Anything you do in the onProgressUpdate, runs on the UI thread

 private class TestAsyncTask extends AsyncTask<Void, String, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            SystemClock.sleep(1000);
            publishProgress("Test");
            SystemClock.sleep(1000);
            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            String test = values[0];
            // Do something with it
        }
    }

protected void onProgressUpdate (Progress... values)

Added in API level 3 Runs on the UI thread after publishProgress(Progress...) is invoked. The specified values are the values passed to publishProgress(Progress...).

Parameters values The values indicating progress.

Upvotes: 1

N J
N J

Reputation: 27505

If you want to use the UI from background thread then use runOnUiThread as below in doInBackground

runOnUiThread(new Runnable(){
        public void run() {
            // update UI
        }

Upvotes: 1

Related Questions