I have implemented a simple timer with CountDownTimer on my game and I need it to start ater a few seconds when the activity is started.
On my main activity's onCreate method, I call this:
playingTime();
Which is as follow
public void playingTime() {
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
String elapsedTime = String.valueOf(millisUntilFinished / 1000);
timer.setText(elapsedTime);
}
public void onFinish() {
timer.setText(R.string.timer_game_over_text);
}
}.start();
}
The timer start normally but immediatelly as the activity is launched. I would like to set a delay before it get executed or if there is a better way to set timer in games. (Count down timer and nomal timer)
You can use the handler in onCreate() method as shown below and playingTime will be called after 1 second
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
playingTime();
}
}, 1000);
You can add delay using Handler like as below:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Executed after YOUR_DELAY_IN_MILLIS
playingTime()
}
}, YOUR_DELAY_IN_MILLIS);
Put the code in your activity onCreate() method
You can set a delay like this :
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
// call method here
}
}, MY_DELAY_IN_MS);
Replace MY_DELAY_IN_MS with your own delay
Related
I need that a button can run automatically every 1-2 seconds, and, when the if condition (that i have in the method which is used by the button) is fulfilled, this function must be stopped.
I've tried this but it wasn't what i wanted because with this code the button only runs one time:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Consulta.performClick();
}
}, 1000);
onClick of my button:
public void consultaBD(View view)
{
DB db = new DB(getApplicationContext(),null,null,1);
String buscar = text_view.getText().toString();
String[] datos;
datos=db.buscar_reg(buscar.trim());
db.infraccion(buscar.trim());
if(datos[2] =="Encontrado")
{
App.matricula=buscar;
startActivity(new Intent(getApplicationContext(), MatriculasActivity.class));
Toast.makeText(getApplicationContext(),datos[2],Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),datos[2],Toast.LENGTH_SHORT).show();
}
}
Another method would be to use Timers to initiate the button click every x seconds. However, in this answer I'll stick with the method you're using. Your handler appears to be incorrect, try something like this instead:
Replace your handler with:
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
#Override
public void run() {
Consulta.performClick();
handler.postDelayed(this, 1000);
}
};
And initiate it with: (where 1000 is the time (in milliseconds) between each execution)
handler.postDelayed(runnable, 1000);
UPDATE:
You have also requested that the event is fired when the text inside of a textbox is changed. To do this, you need to create a new event listener (make sure you replace field1 with the actual reference to your textbox):
field1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
/* Add the Handler Call here */
handler.postDelayed(runnable, 1000);
}
});
whatever context I understood, here is the raw code which may help you.
Handler handler = new Handler();
//initialize this method once by either clicking on button or as the activity starts
void checkAndPerformClick(boolean conditionFulfilled) {
if (conditionFulfilled) {
handler.removeCallbacksAndMessages(null);
return;
}
handler.postDelayed(new Runnable() {
#Override
public void run() {
Consulta.performClick();
checkAndPerformClick(datosEqualsEncontrado());
}
}, 1000);
}
boolean datosEqualsEncontrado() {
// apply your logic here as the name suggests
return false;
}
I want to cyclically update an Android Layout. For this purpose I wrote a short class derived from TimerTask.
Unfortunately my code causes an exception and I do not really know, what the problem might be. :(
So maybe anybody could help.
Thanks
Chris
Here's my code:
In the main activity I've got:
private MyLayoutClass m_MyLayout;
...
public void onCreate(Bundle savedInstanceState)
{
...
m_MyLayout = new AdLayout(this);
Timer caretaker = new Timer();
caretaker.schedule(new MyReloadTimerTask(m_MyLayout), 1000, 5000);
...
}
This is my derived TimerTask class:
public class MyReloadTimerTask extends TimerTask
{
private MyLayoutClass m_MyLayout;
public MyReloadTimerTask(MyLayoutClass aLayout)
{
m_MyLayout = aLayout;
}
#Override
public void run()
{
m_MyLayout.doReload();
}
}
The doReload() cannot be executed, I get an exception with this message: Can't create handler inside thread that has not called Looper.prepare()
Timertask runs on a different thread. So you cannot not update/access ui from a background thread.
Probably m_MyLayout.doReload() is updating ui. Use a Handler or runOnUiThread
runOnUiThread(new Runnable() {
#Override
public void run() {
m_MyLayout.doReload()
}
});
Using Handler
Handler m_handler;
Runnable m_handlerTask ;
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
// do something
m_handler.postDelayed(m_handlerTask, 1000);
// repeat some task every 1 second
}
};
m_handlerTask.run();
To cancel the run
m_handler.removeCallbacks(m_handlerTask);
Im using a Timer to continuously update a TextView, but I'm having trouble restarting the timer during the onResume() method. I use timer.cancel() in the onPause() and onDestroy() methods, but how do I restart the timer in onResume()?
This is my timer code...
int delay = 1000;
int period = 1000;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
//I update the TextView here
}
}, delay, period);
An easier alternative is to use the Handler class. I wouldn't recommend the Timer class because it has no bearing on the life cycle of your Activity and you will have to worry about any potential threading problems yourself. The beauty of using the Handler is that all your callbacks will be on the main thread (so no threading issues to worry about). The following is a simple example on how to do this.
#Override
protected void onCreate(Bundle savedInstanceState)
{
....
mHandler = new Handler();
}
#Override
protected void onResume()
{
mHandler.postDelayed(myRunnable, UPDATE_RATE);
}
#Override
protected void onPause()
{
mHandler.removeCallbacks(myRunnable);
}
private final Runnable myRunnable= new Runnable() {
#Override
public void run()
{
//Do task
mHandler.postDelayed(myRunnable, UPDATE_RATE);
}
}
You dont restart the timer. Instead use a new timer i.e inside onResume() create a new timer. As you are no longer using the previous one, garbage collection will take care of it. So in onResume() use the following code:
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
//update the TextView here
}
}, delay, period);
I am working on a layout which shows a tab like structure on bottom of the layout. Which I need to show on double tap and then hide it after 5 sec. So I am using this countdown timer:
public void timer()
{
cdt=new CountDownTimer(5000,1000) {
#Override
public void onTick(long millisUntilFinished) {
System.out.println("Timer Working"+millisUntilFinished+"");
}
#Override
public void onFinish() {
System.out.println("Finished");
main =(LinearLayout)findViewById(R.id.parent);
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams)main.getLayoutParams();
mlp.height=420;
set_up_views();
find_module();
tl.setVisibility(View.INVISIBLE);
}
}.start();
}
But I dont know how to stop and restart this timer. How can I do?
I suggest you not to Use CountDownTimer for this case.
Use Handler.postDelayed(Runnable runnable, long delay)
public class yourActivity extends Activity
{
public Handler handler = new Handler();
...
public void hideAfter5Sec()
{
handler.postDelayed(new Runnable()
{
View view = findViewById(view_to_hide);
view.setVisibility(View.INVISIBLE);
}, 5000);
}
}
postDelayed will execute that code after 5Sec.
EDITED:
postDelayed will be call only once after 5 Sec through Lopper.loop(). If there are multiple call to hideAfter5Sec() then only you will get multiple call to postDelayed.
If you have multiple call hideAfter5Sec() i dont think there is any wrong because hideAfter5Sec() is just hidding it. so if it one or many your view will be hidden.
If in case you want to hide only in the last call of hideAfter5Sec() use this variant.
public class yourActivity extends Activity
{
public Handler handler = new Handler();
public long lastHideAfter5Sec = 0L;
...
public void hideAfter5Sec()
{
lastHideAfter5Sec = System.currentTimeMillis();
handler.postDelayed(new Runnable()
{
if(System.currentTimeMillis() - lastHideAfter5Sec < 5000)
return;
View view = findViewById(view_to_hide);
view.setVisibility(View.INVISIBLE);
}, 5000);
}
CountDownTimer.cancel() is not working in the below code:
myTimer = new CountDownTimer(10000, 1000) {
public void onFinish() {
}
#Override
public void onTick(long millisUntilFinished) {
if(null != myObject){
myTimer.cancel();
}
}
}.start();
In the above code I have started a CountDownTimer which check if the object is not null and cancels the Timer accordingly. The object is set by some listener at any point of time.
Please refer and suggest. Am I doing the right thing here?
Solution By Gautier Hayoun :
Just made a drop-in replacement for
CountDownTimer that you can cancel
from within onTick : Github link–
Gautier Hayoun Dec 12 '10 at 1:04
Solution By Gautier Hayoun :
Just made a drop-in replacement for CountDownTimer that you can cancel from within onTick : Github link– Gautier Hayoun Dec 12 '10 at 1:04
Instead of CountDownTimer use TimerTask
final static long INTERVAL=1000;
final static long TIMEOUT=10000;
TimerTask task=new TimerTask(){
#Override
public void run() {
elapsed+=INTERVAL;
if(elapsed>=TIMEOUT){
this.cancel();
displayText("finished");
return;
}
//if(some other conditions)
// this.cancel();
displayText("seconds elapsed: " + elapsed / 1000);
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, INTERVAL, INTERVAL);
private void displayText(final String text){
this.runOnUiThread(new Runnable(){
#Override
public void run() {
mTextField.setText(text);
}
});
}