How do I set up a Timer.scheduleAtFixedRate() that actually works?
Using an actual Timer (java.util.Timer) in conjunction with runOnUiThread() is one way to solve this issue, and below is an example of how to implement it.
public class myActivity extends Activity {
private Timer myTimer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
TimerMethod();
}
}, 0, 1000);
}
private void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
//Do something to the UI thread here
}
};
}
SOURCE: http://steve.odyfamily.com/?p=12
Seth Schaffner
A green programmer currently learning Java for Android. Looking to make games.
Updated on June 04, 2022Comments
-
Seth Schaffner almost 2 years
I am using Eclipse for Android. I am trying to make a simple repeating Timer that has a short delay. It will start after a TextView timerTV is clicked. This code is in the onCreate method:
timerTV = (TextView) findViewById(R.id.timerTV); timerTV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Timer gameTimer = new Timer(); TimerTask doThis; int delay = 5000; // delay for 5 sec. int period = 1000; // repeat every sec. doThis = new TimerTask() { public void run() { Toast.makeText(getApplicationContext(), "timer is running", Toast.LENGTH_SHORT).show(); } }; gameTimer.scheduleAtFixedRate(doThis, delay, period);
Everytime I try to run it, a "Class File Editor" pops up with the error: "Source not found" The JAR file C:\Program Files\Android\android-sdk\platforms\android-8\android.jar has no source attachment. You can attach the source by clicking Attach Source below: [Attach Source...] When I click this, Eclipse asks me to select the location folder containing 'android.jar' I tried to do this, but cannot navigate all the way to the folder it is located in anyway.
I presume the issue is in my code somewhere. I have been searching for hours, even copied and pasted code many times.