Print Shortlink

Dive into Android Development – IV

Like many other native applications, Android applications are also single threaded.  There is only one thread ie., the UI thread in the application. So for performing a continuous activity, you need to create a separate worker thread and run it. But you cannot update the UI components from that worker thread you have created. UI components have to be played upon only from the UI thread, failing to do so will lead to unpleasant user experience.
Android provides a number of ways to update UI components from a different worker thread. One of them is using the runOnUiThread method on Activity class, which accepts the Runnable object.
Say you want to display the current date and time in a TextView object from a separate thread. This is how you can do it.
   
    final TextView dateTxt = (TextView)findViewById(R.id.dateTxtView);
    this.runOnUiThread(new Runnable(){
        public void run(){
                      dateTxt.setText(new Date().toString());
        }
    });
dateTxtView is a TextView component. This code starts a separate thread but accesses the dateTxt component from the UI thread only.
What if you want to update the time every one second, let’s use a java.util.Timer class for this purpose. The Timer will run for 1000 milliseconds. The code is shown below.
   
    final TextView dateTxt = (TextView)findViewById(R.id.dateTxtView);
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
             public void run() {
                 runOnUiThread(new Runnable(){
                    public void run() {
                       dateTxt.setText(new Date().toString());
                    }
                 });
            }
    }, 0, 1000);

The Timer class’ schedule method accepts a TimerTask instance that starts a thread, after a delay of 0 seconds, and runs every 1000 milliseconds . This thread encapsulates another worker thread that updates the dateTxt with the latest time.

Page 1 of 1

3 Responses

  1. Muthu Natarajan

    Sir,
    Your tutorials are fantastic.
    I’m currently developing android apps for real-time video processing..
    I wanna implement interaction with the system with markers in front of camera…

    I have reached the point where i can get the (x,y) co-ordinates of the marker’s central point…
    Now with this i wanna make it interact to the system..and define actions like swipe,select etc..
    What should i do exactly at this stage

  2. Muthu Natarajan

    Thank u for replying on such short notice :)

    My query is focused only controlling the interface..
    The basic interface is the touch & touch gestures..
    Are there any methods to influence these activities??
    Or should I enter into kernel level & edit the drivers??

Leave a Reply to Muthu Natarajan Click here to cancel reply.