I want to use CountDownTimer within a for loop but when I am using following code then CountDownTimer is running only once while I want to run it CountDownTimer as per given condition in for loop. it might be a silly question but I will be very thankful to you if I get some help. Thanks in Advance
for (int i=1;i<=10;i++){
Random random = new Random();
totalques.setText(String.valueOf(i) + "/10");
firstnum.setText(String.valueOf(random.nextInt(100)));
secondnum.setText(String.valueOf(random.nextInt(50)));
new CountDownTimer(5000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
time.setText(String.valueOf(millisUntilFinished / 1000)
+"s");
}
#Override
public void onFinish() {
}
}.start();
}
You can use the Timer class for doing your job
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
//one second elapsed
}
});
}
};
timer.schedule(timerTask, 0, 1000);
The schedule method say start directly and I want to be notified when every 1000 milliseconds elapse.
Don't forget to cancel the timer when you want to stop it with timer.cancel()
Inside the run you can decrement an int and when it reach 0 you can stop the timer
Related
I have requirement to implement, In my activity, I receive an OTP for login, the OTP has be expired in 90 seconds.
Questions
1> Is Alarm Manager is best way to implement the 90 second time expiry?
2> If I have received OTP and same time I receive a call and when call is ended after 90 seconds and when i come back to original
activity , user should be shown a pop up saying OTP has been expired?
any help will be appreciated.
Thanks
Use CountDownTimer
new CountDownTimer(90000, 1000) {
public void onTick(long millisUntilFinished) {
Log.d("seconds remaining: " , millisUntilFinished / 1000);
}
public void onFinish() {
// Called after timer finishes
}
}.start();
You can use TimerTask like below sample :
public class AndroidTimerTaskExample extends Activity {
Timer timer;
TimerTask timerTask;
//we are going to use a handler to be able to run in our TimerTask
final Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
//onResume we start our timer so it can start when the app comes from the background
startTimer();
}
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
timer.schedule(timerTask, 5000, 10000); //
}
public void stoptimertask(View v) {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {
//get the current timeStamp
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
final String strDate = simpleDateFormat.format(calendar.getTime());
//show the toast
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(), strDate, duration);
toast.show();
}
});
}
};
}}
You can change start and stop of Task as per your call and initialise too whenever you want.
So I am trying to display the time passed since pressing a button on my app.
My code is:
/*This will initiate the timer*/
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
start=System.currentTimeMillis();
time=System.currentTimeMillis()-start;
currenttimedisplay.setText(Long.toString(time));
}
});
}
}, 0, 1000);
The app runs but when I press the button it just shows "0.0".
The app doesn't close out. Any help is appreciated!
Please try this:
/*This will initiate the timer*/
timer = new Timer();
start=System.currentTimeMillis();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
time=System.currentTimeMillis()-start;
currenttimedisplay.setText(Long.toString(time));
}
});
}
}, 0, 1000);
In your code, the value of start is changed everytime the timer elapsed (start = System.currentTimeMillis()), so the value of time is always 0 (System.currentTimeMillis() - System.currentTimeMillis() should be 0 if it is called with no, or very small time difference...). So you should set the value of start on button press, then calculate the difference, and update text view in your timer task.
Sorry for my English! :)
Ok, I want to repeat something multiple times every second - like here:
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//Called each time when 1000 milliseconds (1 second) (the period parameter)
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);
Now, inside it I want to generate random number between 1-3 (including) and do something if it is 3.
So:
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Random rand = new Random();
int num = rand.nextInt(3)+1;
if(num==3){
// repeat action here.
}
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);
And inside the if statement, I want to repeat other action (moving ImageView every 5 milliseconds or something like this). How can I do it? Thank you.
You can use either a CountDownTimer
http://developer.android.com/reference/android/os/CountDownTimer.html
e.g. create a CountDownTimer for 30secs (30000ms) and notify each second (1000ms)
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
//I get called every 1000ms
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
or just a Handler.
http://developer.android.com/reference/android/os/Handler.html
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
//dostuff
handler.postDelayed(this,1000); //repeat after a second
}
});
For animations you should have a look at ObjectAnimator/ViewPropertyAnimation.
I have tried multiple ways to have a single persistent timer update the ui in multiple activities, and nothing seems to work. I have tried an AsyncTask, a Handler, and a CountDownTimer. The code below does not execute the first Log.i statement.... Is there a better way to start the timer (which must be called from another class) in Main (which is the only persistent class)?
public static void MainLawTimer()
{
MainActivity.lawTimer = new CountDownTimer(MainActivity.timeLeft, 1000)
{
public void onTick(long millisUntilFinished)
{
Log.i("aaa","Timer running. Time left: "+MainActivity.timeLeft);
MainActivity.timeLeft--;
if(MainActivity.timeLeft<=0)
{
//do stuff
}
else
{
//call method in another class
}
}
public void onFinish()
{ }
}.start();
}
To clarify my problem:
When I run the code the Log.i("aaa","Timer running") statement is never shown in the log, and the CountDownTimer never seems to start. MainLawTimer is called from another class only (not within the same class.
For CountDownTimer
http://developer.android.com/reference/android/os/CountDownTimer.html
You can use a Handler
Handler m_handler;
Runnable m_handlerTask ;
int timeleft=100;
m_handler = new Handler();
#Override
public void run() {
if(timeleft>=0)
{
// do stuff
Log.i("timeleft",""+timeleft);
timeleft--;
}
else
{
m_handler.removeCallbacks(m_handlerTask); // cancel run
}
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
Timer
int timeleft=100;
Timer _t = new Timer();
_t.scheduleAtFixedRate( new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
Log.i("timeleft",""+timeleft);
//update ui
}
});
if(timeleft>==0)
{
timeleft--;
}
else
{
_t.cancel();
}
}
}, 1000, 1000 );
You can use a AsyncTask or a Timer or a CountDownTimer.
Thank you all for your help, I discovered the error in my code... timeLeft was in seconds rather then milliseconds. Since timeLeft was under 1000 (the wait period) the timer never started.
I want to show a text view with elapsed seconds from 60 to 1.
How should I take handler event?
time = GetTime.Showtime();
elapsetime.setText(time + " Secs");
Use a CountDownTimer, http://developer.android.com/reference/android/os/CountDownTimer.html
First of all, you have to create and initialize Timer object:
Timer myTimer;
myTimer = new Timer();
After that you can call use the schedule method to call timerMethod() (or your method). It will the timerMethod() every second (1000 milliseconds).
myTimer.schedule(new TimerTask() {
#Override
public void run() {
timerMethod();
}
}, 0, 1000);
//Runs your doSomething() in the UI Thread
private void timerMethod()
{
this.runOnUiThread(doSomething);
}
// make your doSomething() runnable
private Runnable doSomething = new Runnable() {
public void run() {
// Your code for doing something
}
i use handler thread runnable.
handler =new Handler();
runnable = new Runnable() {
#Override
public void run() {
elapsetime.setText(time+" Secs");
time--;
if(time<1){
handler.removeCallbacks(runnable);
}else{
handler.postDelayed(this, 1000);
}
}
};
handler.postDelayed(runnable, 1000);