0

my Activity shows to the user some data, which are download from a web server. Data could change over the time, so the web server communicates new updates to the connected clients.

So the work of my application is basically this:

while ( true ) {
   wait for updates;
   update the UI;
}

This code could run forever, and during its life it should update the UI many times.

What class should I use to implement this code?

Thread or Runnable seems the easiest solutions to my problem, but how could I comunicate to the UI thread?

optimusfrenk
  • 1,271
  • 2
  • 16
  • 34
  • have you decided whether its gonna be 'pull' or 'push' .. that drives some choices on sync protocols.... – Robert Rowntree Sep 24 '15 at 14:42
  • IMO - you could look at PubSub (rabbitmq) so that your server, on stateChanges, just publishes once... The combo of rabbit and active clients with active Sessions can just do the rabbit equivalent of 'refresh' on a suitable interval. I believe that just 'pulls' any updates to a clients timeline. – Robert Rowntree Sep 24 '15 at 14:52
  • Thanks #Robert, but my problem is related to the fact that the long network operation is not running on the UI thread, so if this thread try to update the UI an exception is raised. – optimusfrenk Sep 24 '15 at 15:06
  • pass a 'Handler' ref into your thread. As state changes in the thread, just 'obtain/send' msgs via the handler. UI responds to messages from the thread, parsing msg.body and refreshing UI. – Robert Rowntree Sep 24 '15 at 15:15

2 Answers2

0

You should probably go with an asyncTask, calling runOnUiThread when you need to update the UI. Have a look to this question to see how activity.runOnUiThread() should be used

IMHO AsyncTask is preferrable, because it gives you more fine-grained control over your background task via onPreExecute(), onPostExecute()

Community
  • 1
  • 1
Shine
  • 3,788
  • 1
  • 36
  • 59
  • I will try this solution, but I have to create a new ``AsyncTask`` after every update. It is a bit strange this usage of ``AsyncTask``, in my opinion. – optimusfrenk Sep 24 '15 at 15:10
  • Be noted that AsyncTask is not suitable for longer operations, there are many known issues. – Naveen Niraula Feb 10 '18 at 15:46
0

onServerChangesListener... refresh UI

public void serverStateWrappr(){

Handler messageHandler = new Handler() {            
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        _localstr = getStuff((String) msg.obj)
        updateAdapter(_localstr)
    }}

from the thread which has a handleRef ...

            while (onChangesForClient) {                 
                    Message msg = Message.obtain();
                    msg.what=1;
                    msg.obj=newData;
                    //TODO this is the comment for UI 
                    mhandleRef.sendMessage(msg);
                }
            }
Robert Rowntree
  • 6,230
  • 2
  • 24
  • 43