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.
Related
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
App crashes, I am unable to use the same view in Timer Class
I need the app to refresh a value and display it
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)
find(v);
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
10000);
public void find(View view) {
if (btAdapter.isDiscovering()) {
//the button is pressed when it discovers, so cancel the discovery
btAdapter.cancelDiscovery();
} else {
BTArrayAdapter.clear();
btAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
Usually in this situation you need to use Activity.runOnUiThread()
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)
runOnUiThread(new Runnable() {
public void run() {find(v);}
});
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
10000);
For a simple Timer App I try to add a TextView to my app that says something like "15 seconds remaining", obviously this changes every seccond until it finally changes to "time up!". My idea was to use a loop like this:
while(now<endTime):
remaining=endTime-now;
text.setText(remaining);
While this could work, I am unsure if this is the right approach or if theres a better option.
You can use a handler to do it as below:
Handler myHandler=new Handler();
myHandler.postDelayed(timer, 1000);
private Runnable timer= new Runnable() {
public void run() {
if(counter==15){
textview.setText("Time Up");
counter=0;
}
else{
counter++;
textview.setText(counter+ " remaining");}
}
};
Use a CountDownTimer, instead.
I use this code snippet to achive a similar result:
final int secs = 5;
new CountDownTimer((secs +1) * 1000, 1000) // Wait 5 secs, tick every 1 sec
{
#Override
public final void onTick(final long millisUntilFinished)
{
txtCount.setText("" + (int) (millisUntilFinished * .001f));
}
#Override
public final void onFinish()
{
txtCount.setText("GO!");
}
}.start();
In the onFinish() handler you can do the "elapsed time" stuff
How to schedule a function every defined time with the option to change this time?
I found that I can do it using timer & timerTask or handler. The problem that it dosen't repeats the time I defined, it repeats randomaly...
runnable = new Runnable() {
#Override
public void run() {
//some action
handler.postDelayed(this, interval);
}
};
int hours = settings.getIntervalHours();
int minutes = settings.getIntervalMinutes();
long interval = (hours * 60 + minutes) * 60000;
changeTimerPeriod(interval);
private void changeTimerPeriod(long period) {
handler.removeCallbacks(runnable);
interval = period;
runnable.run();
}
Use a Handler object in the onCreate method. Its postDelayed method causes the Runnable parameter to be added to the message queue and to be run after the specified amount of time elapses (that is 0 in given example). Then this will queue itself after fixed rate of time (1000 millis in this example).
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
android.os.Handler customHandler = new android.os.Handler();
customHandler.postDelayed(updateTimerThread, 0);
}
private Runnable updateTimerThread = new Runnable()
{
public void run()
{
//write here whaterver you want to repeat
customHandler.postDelayed(this, 1000);
}
};
I used the solution here
But in the code where the handler was initialized, I used
mHandler = new Handler(getMainLooper);
instead of
mHandler = new Handler();
which worked for me
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);