Thursday 23 December 2010

Custom Timer for Android OS (with Cross Thread Messaging to Handle the UI updates )

Code below shows MyTimer class which implements the Runnable interface in order to be run as an individual thread. This class also supports MyTimerListener to inform the classes which are registered to this class, onTick event.

MyTimerClass

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MyTimer implements Runnable {

long interval;
List<MyTimerListener> l = new ArrayList<MyTimerListener>();
@Override
public void run() {
while(true)
{
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Iterator<MyTimerListener> it = l.iterator();
while(it.hasNext())
{
((MyTimerListener)it.next()).onTick();
}
}

}
MyTimer(long Interval)
{
interval=Interval;
}
public void addListener(MyTimerListener mtl)
{
if(!l.contains(mtl))
l.add(mtl);
}
public void removeListener(MyTimerListener mtl)
{
if(l.contains(mtl))
l.remove(mtl);
}
public void start()
{
Thread t = new Thread(this);
t.start();
}

}



MyTimerListerner interface responsible for handling the onTick event.


public interface MyTimerListener {
void onTick();
}



Implementation of MyTimer


android.os.Handler;

public class AttachedClass implements MyTimerListener {

private MyTimer mt = new MyTimer(1);
private Handler mHandler = new Handler();// Main thread attaaches this handler itself while it creates the instance of AttachedClass instance
public void startAttachedClass()
{
mt.start();// start method creates a new thread and runs mt in it.
}
@Override
public void onTick() {
Runnable r = new Runnable() {
public void run() {
TextView1.setText("Text has setted");
}
};
mHandler.post(r);// onTick event called by new thread which has been created in mt.start(). but TextView1 belonges to the main thread. In order to make handled setText method by new thread, Handler's post method has used which requires a Runnable(method) which will be run in main thread.

}
}
}


You can leave your questions to the comment section. Than you..

No comments: