views:

45

answers:

1

Hi Everyone, I am hoping you can help me:

I need to update my ui for an android app and I'm trying to use the Handler class to do it, using http://developer.android.com/resources/articles/timed-ui-updates.html and the android developer resources "Common Task" for using Handlers as guides.

Basically, I need something between the two - a timed update of the user interface, but without a button. So here is the relevent code that I am working on. All help is greatly appreciated.

public class Activity1 extends Activity {

[… variables]

final Handler mHandler = new Handler();

final Runnable mUpdateResults = new Runnable() {
    public void run() {

        UpdateDisplay();
        mHandler.postDelayed(mUpdateResults, 200);
    }
};


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

[…]

startLongRunningOperation();

}


protected void startLongRunningOperation() {

    Thread t = new Thread() {
        public void run() {
             if (mStartTime == 0L) {
                 mStartTime = System.currentTimeMillis();
                 mHandler.postDelayed(mUpdateResults, 200);}
            mHandler.post(mUpdateResults);
        }
    };
    t.start();
}

Thanks again!

A: 

On Android it's best to use AsyncTask to execute tasks in the background while (progressively) updating UI with results from this task.

Edited:

After checking code I think your Handler works correctly. Probably problem is in UpdateDisplay()'. Since you are updating display from background thread, make sure you callview.postInvalidate()` after you're done updating your View.

Peter Knego
My problem is that that handler code doesn't update my ui at regular intervals at all - it just displays my ui without updates. So I need to know what I'm doing wrong.And thank you, Peter for the suggestion - I'm looking into your suggestion now.
QueryMan