Android: the right way to pass a message from a background thread to a user interface thread?

I read a lot about threads, handlers, loopers, etc., and I'm very confused. In my application, I want the first activity to start a background worker. This background worker will constantly request data from the TCP socket and (hopefully) put new information into the user interface stream as the data arrives. If the user moves on to a new action, the background should continue to do this, but only send different messages to the user interface stream so that it can update the new layout accordingly.

here is what i still have ... This is in my main activity file

public class MyTCPTest extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // set the layout
        setContentView(R.layout.main);
        // create a handler to handle messages from bg thread
        Handler handler = new Handler();

        BgWorkerThread bgw = new BgWorkerThread();
        bgw.start();
 }

in another file, I define my workflow as this ...

public class BgWorkerThread extends Thread {    
@Override
public void run(){

    while(true)
    {
        try {
        // simulate a delay (send request for data, receive and interpret response) 
        sleep(1000);

                    // How do I send data here to the UI thread?

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
} 

, ? , , ? , , . ?

, , bgworker , , . ? BgWorkerThread, , Activity ?

+5
3

SO-. , , :

  • , mapInd ( , ). Activity, , - Activity (, , ).
  • AsyncTask Threading Model, onProgressUpdate, , Background Thread

/ BackgroundThread

public class ResponseHandler extends AsyncTask<Void, String, Integer> {
    boolean isConnectionClosed = false;
    Map<Integer, Handler> requestIdToMapHandler;

    public ResponseHandler() {
        this.requestIdToMapHandler = new HashMap<Integer, Handler>();
    }

    @Override
    protected Integer doInBackground(Void... params) {
        int errorCode = 0;

        try {
            // while not connection is not close
            while(!isConnectionClosed){
                // blocking call from the device/server
                String responseData = getResponse();

                // once you get the data, you publish the progress
                // this would be executed in the UI Thread
                publishProgress(responseData);
            }
        } catch(Exception e) {
            // error handling code that assigns appropriate error code
        }

        return errorCode;

    }

    @Override
    protected void onPostExecute(Integer errorCode) {
        // handle error on UI Thread
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        String responseData = values[0];

        // the response contains the requestId that we need to extract
        int requestId = extractId(responseData);

        // next use the requestId to get the appropriate handler
        Handler uiHandler = getUIHandler(requestId);

        // send the message with data, note that this is just the illustration
        // your data not necessary be jut String
        Message message = uiHandler.obtainMessage();
        message.obj = responseData;
        uiHandler.sendMessage(message);
    }

    /***
     * Stub code for illustration only
     * Get the handler from the Map of requestId map to a Handler that you register from the UI
     * @param requestId Request id that is mapped to a particular handler
     * @return
     */
    private Handler getUIHandler(int requestId) {
        return null;
    }

    /***
     * Stub code for illustration only, parse the response and get the request Id
     * @param responseId
     * @return
     */
    private int extractId(String responseId) {
        return 0;
    }

    /***
     * Stub code for illustration only
     * Call the server to get the TCP data. This is a blocking socket call that wait
     * for the server response
     * @return
     */
    private String getResponse() {
        return null;
    }
}
+3

, UI. : [ ] - ?. , , Handler, sendEmptyMessage(). , , .

, .

+1

runOnUIThread(new Runnable {

public void run() {
//Update your UI here like update text view or imageview etc

}

});
0

All Articles