Mar 12, 2013

runOnUiThread, runs the specified action on the UI thread

The method runOnUiThread(Runnable action) runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

Example:

package com.example.androidrunnable;

import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {
 
 static TextView prompt;
 static int counter;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        prompt = new TextView(this);
        setContentView(prompt);
        
        prompt.setText("Hello");
        
        Thread myThread = new Thread(myRunnable);
        myThread.start();
    }

    Runnable myRunnable = new Runnable(){

  @Override
  public void run() {
   counter = 0;
   while(true){
    try {
     Thread.sleep(1000);
     runOnUiThread(new Runnable(){

      @Override
      public void run() {
       prompt.setText(String.valueOf(counter));
      }
      
     });
     counter++;
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  } 
    };

}


No comments:

Post a Comment

Infolinks In Text Ads