I just recently started playing around with Java/Android.
I am trying to make a very simple Android app. I want a number to be progressively increased. Something like:
int x = 0;
then every 0.1 seconds, x++. Then I can set the text of a textview
.setText(String.valueOf(x));
So in the program it will have an integer number increasing from 0 by 1 every 0.1 seconds.
Meanwhile all other functions/code should run normally while this is happening in the background
you could use the TextView's internal handler and its postDelayed method, to increment the int . E.g.
textView.postDelayed(new Runnable() {
#Override
public void run() {
textView.setText(String.valueOf(++x));
textView.postDelayed(this, 100);
}
}, 100);
where 100 is 100 milliseconds. Don't forget to call
textView.removeCallbacks(null);
when your activity is paused
you can use:
int x = 0;
TimerTask scanTask;
Timer t = new Timer();
public void incrementValue(){
scanTask = new TimerTask() {
public void run() {
x++;
}};
t.schedule(scanTask, 100, 100);
}
and use t.cancel(); whenever you want to stop the task.
Related
I'm trying to make an image twinkle with RaffleImage(); while I'm executing the timer, my character is immune to any collision, I want it to be immune only for 2 seconds, so the timer get execute only for 2 seconds and then get finished.
I've tried subtracting System.currentTimeMillis() but any variable I create from this method, have always the same value, making me get a zero from that subtracting.
Do you know how I can stop or pause the timer after any elapsed time in seconds?
immuneTimer = new Timer(50, new ActionListener() {
#Override
public synchronized void actionPerformed(ActionEvent e) {
long initMillis = System.currentTimeMillis();
if (System.currentTimeMillis() - initMillis > 2000 ) { // this substract gives me 0
initImages();
setImmune(false); // so this never reached
immuneTimer.stop();
} else {
raffleImage(); //its executing like forever;
}
}
});
The Swing timer fires a an ActionEvent. From the event you can use getSource() to get the source of the event. Cast that source to the swing timer object and use that to turn it off.
To know when to turn it off you need to have a variable count the number of times the swing timer is invoked. When the variable reaches that amount, turn it off.
int elapsedTime = 0;
int timerDelay = 50;
int max = 2000;
public void actionPerformed(ActionEvent ae) {
elapsedTime += timerDelay; // you could use getDelay here but it
// is in milliseconds.
if (elapsedTime >= max) {
Timer s = (Timer)ae.getSource();
s.stop();
}
// rest of code
}
I want to check if an int value is higher than 20 for a certain amount of 15 minutes, if that int value stays higher than 20 in those 15 minutes, code will executed
I didn't understand the difference between a Handler and a Runnable, how to use them, What do they do...
My question is:
How can I run an if statement for a certain time using a Runnable/Handler
This is the if statement which I want to be checked for 15 mins,
if(Speed > 20){
// Code that will run after 15 mins IF the speed is higher than 20 for all that time
}
add this, this timer will execute after 1 sec you can add your time you want and put your if statement inside run function
private Timer myTimer;
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 1000);
Try using below code. It uses a while loop which will keep of looping for-ever until two condition are met
1) i becomes greater than 20
2) flag is set to false
For each iteration, it will sleep for 1 minute
public static void main(String[] args) {
int i = 0;
boolean flag = true;
try {
while (i < 20 && flag) {
TimeUnit.MINUTES.sleep(1);
// Expecting some logic to increment the value of i
// Or change the flag value of this to exit the while loop
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
I am making a quiz using Java . I want user to get only 1 minute to answer the question.After 1 minute next question which is is next frame should be displayed . How can i do that without using threads?*
try a Timer:
int delay = 0;
int period = 60000;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
//jump to your next question
});
}
}, delay, period);
Why is this Code not working ?
This code should extend the Countdowntimer to 10 sec (everytime when point is 20 , 40 , 60) etc.But when I start it and my score is by 20 it shows in a TextView a right value of time.But then it is gone in 1 sec and the Countdowntimer got the old value and continue.Someone a idea ?
int bonus_time = 1 , sec = 10000 , point == 0;
points_timer =new CountDownTimer(sec,1000) {
#Override
public void onTick(long millisUntilFinished)
{
if ( point == (bonus_time * 20))
{
++bonus_time;
millisUntilFinished += 10000;
sec += 10000;
}
++point;
}
#Override
public void onFinish()
{
bonus_time = 1;
}
};
When you create a timer with the sec variable for its time, it does not magically connect the two so when the value of sec changes the timer's time changes, it just uses the value of sec once when you make the timer.
Same goes for changing millisUntilFinished, it's a parameter you got from a callback, by changing its value you are not doing anything.
The only way to change a timer's time is to create a new one. This is my suggestion:
// GLOBAL VARIABLES
CountDownTimer points_timer;
int bonus_time = 1 , sec = 10000 , point == 0;
public void createTimer()
{
points_timer =new CountDownTimer(sec,1000) {
#Override
public void onTick(long millisUntilFinished)
{
sec = millisUntilFinished;
if ( point == (bonus_time * 20))
{
++bonus_time;
//millisUntilFinished += 10000;
sec += 10000;
createTimer();
}
++point;
}
#Override
public void onFinish()
{
bonus_time = 1;
}
};
}
The creation of the timer is surrounded by a function, and that function is called each time the bonus is gained to recreate the timer with the new value of sec.
You should also call that method once in place of your previous code, to initially create the timer.
Hope this works..
There is no way to extend a CountDownTimer, no method in the class provides this.
Your attempt to add time to sec is useless, I even wonder how it can compile. Anyway, in Java integers are passed by value, so once you passed 1000, you passed it and can't change that value.
The only alernative is to re-create a new timer and use it instead of the old one. Or recode everything, a timer of your own that you can extend.
in
public void onTick(long millisUntilFinished)
you do
millisUntilFinished += 10000;
you can not assign to primitive parameter and expect that it changes anything outside of that method (eg. scope of millisUntilFinished is onTick method and nothing more)
I know I am probably way off here, but I am trying to create a timer array so that mytimer[0] mytimer[1], mytimer[2], etc... all fire off at a different interval, with diffrerent events sent to a server. Any ideas? The for loop value of 6 is an organic number for testing purposes only. This number would later be decided base on a setting from the program's xml file.
Timer mytimers[] = new Timer[6];
for(int i = 0;i < 6;i++){
final int mytime = i;
mytimers[i].scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//do action
sendData("Timer " + mytime + " fired");
}
}, 10000, i*1000);
}
Timer mytimers[] = new Timer();
I'm assuming this is the line that doesn't work? You can't initialize an array with an object; initialize it with an array:
Timer mytimers[] = new Timer[6];
Making another guess, you're also not initializing the individual timers:
mytimers[i].scheduleAtFixedRate(new TimerTask() {
At this point mytimers[i] isn't set to anything, so how can you call scheduleAtFixedRate on it? Initialize it first:
mytimers[i] = new Timer();
mytimers[i].scheduleAtFixedRate(new TimerTask() {
EDIT:
Your "IllegalArgumentException: Non-positive period." is because on the first time through the loop, i = 0, so i * 1000 = 0, and the period can't be 0 ("run this event every 0 zero seconds").
Start with i = 1 and it should be fine.
Have you thought about just doing one timer, and the putting all the different events in some sort of (if timeElapsed % timerinterval[1] == 0) and then that way you can simulate the different times by using just one timer. Then you only need an array of integers with the timer interval.
Use this:
Timer mytimers[] = new Timer[6];
for(int i = 0;i < 6;i++){
mytimers[i] = new Timer();
final int mytime = i;
mytimers[i].scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//do action
sendData("Timer " + mytime + " fired");
}
}, 10000, i*1000);
}
The problem is, you are calling the Timer() constructor on an array and never initializing your individual timers. Rather, you should initialize the array as an array and the individual timers as timers.