Wednesday, August 31, 2011

TimerClass for Android C# style

Here is an example re-usable timer code. You just need to write your code in the Run Methods
This will be easy for those who are migrating from C#

class EBTimerTask extends TimerTask
{
Activity _parent;

public void SetParent(Activity parent)
{
_parent = (Activity) parent;

}

@Override
public void run()
{
//Write your code to execute in timer thread here
//Blah ...blah..blah..

//If you application need to update UI elements write those conde in the
//Timer action run method
EBTimerAction timerAction = new EBTimerAction();
timerAction.SetParent(_parent);
_parent.runOnUiThread(timerAction);
}
}

class EBTimerAction implements Runnable
{
Activity _parent;
Drawable _curImage;

public void SetParent(Activity parent)
{
_parent = (Activity) parent;

}

@Override
public void run()
{
//Safe to update UI elements from here
//Collect UI element pointers by using findViewById and use it here
}
}


Call it like this from your Activity Class

EBTimerTask task = new EBTimerTask();
task.SetParent(this);

timer1 = new Timer();
timer1.schedule(task, 0, 50);

No comments: