Martin Li
Martin Li

Reputation: 23

TimerTask can not update UI?

 new Timer().schedule(new TimerTask() {

        public void run() {
            KeyBoardUtil.showKeyBoard(et_search);
        }
    }, 300);

I show the keyboard use TimerTask,and it runs fine. how to explain it?

Upvotes: 0

Views: 1127

Answers (1)

Ahmad Aghazadeh
Ahmad Aghazadeh

Reputation: 17131

You can use runOnUiThread :

   runOnUiThread(new Runnable(){
        public void run() {
             // Your code
        }
    });

Or

Handler mainHandler = new Handler(context.getMainLooper());

Runnable myRunnable = new Runnable() {
    @Override 
    public void run() {
        // Your code
    }  
};
mainHandler.post(myRunnable);

developer.android.com

In the previous lesson you learned how to start a task on a thread managed by ThreadPoolExecutor. This final lesson shows you how to send data from the task to objects running on the user interface (UI) thread. This feature allows your tasks to do background work and then move the results to UI elements such as bitmaps.

Every app has its own special thread that runs UI objects such as View objects; this thread is called the UI thread. Only objects running on the UI thread have access to other objects on that thread. Because tasks that you run on a thread from a thread pool aren't running on your UI thread, they don't have access to UI objects. To move data from a background thread to the UI thread, use a Handler that's running on the UI thread.

Upvotes: 5

Related Questions