help with Handler class to update UI - Android
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 开发者_如何学C== 0L) {
mStartTime = System.currentTimeMillis();
mHandler.postDelayed(mUpdateResults, 200);}
mHandler.post(mUpdateResults);
}
};
t.start();
}
Thanks again!
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 call [view.postInvalidate()][2]
after you're done updating your View.
精彩评论