giving a variable the value of one every 30 seconds - java

In android if a button is clicked i want a countdown to start from 30 and countdown to 0. I created a code with a basic countdown method but the problem is it doesn't continue to countdown if the activity or application closes.
What i want to do is for the activity or just the countdown to continue ticking down in the background until it hits 0 in which it'll change variable B to the value of 1.
I have expanded from my original model thinking i could compare dates times from when the button was clicked + 30 seconds to when the activity is called up upon again. But so far i have come to a stump in comparing two datetimes in android.
Any help?

What you likely want is an async task to run in the background. Something like:
private class JohnnysPollTask extends AsyncTask<Integer, Void, Integer> {
/**
* The system calls this to perform work in a worker thread and delivers
* it the parameters given to AsyncTask.execute()
*/
protected Integer doInBackground(Integer... millis) {
try {
int waited = 0;
int duration = 30000;
while (waited < duration) {
Thread.sleep(1000);
waited += 1000;
if (waited>=duration) {
b=1;
break;
}
}
} catch (InterruptedException e) {
// do nothing
}
return 1;
}

Implement CountDownTimer
inside service.

You could try using a service instead of an activity.

Related

Android Studio Delay inside Loop

I want to make a loop, the times the user wants but with a delay of 3 seconds.
This is the code:
for (i = 0;i < n1; i++){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Toast.makeText(KeyMapCreator.this, "Try number " + i,Toast.LENGTH_SHORT).show(); ActionIwantToDo();
}
},3000);
}
The variable i is the one that the user sets.
The problem is that the toast doesn't show up every 3 seconds, it just do like a normal loop without delay. I thought it was because of the time of the toast but if i set the time to 20 secs still being the same.
Someone knows how to make a proper delay inside a loop???
The problem you have is that your loop creates many handlers at once that delay for 3 seconds and then show a toast. They do not wait for each other, and because they are created within milliseconds of each other they will show the toast at the same time.
I'm not sure what you are trying to accomplish, and a loop is probably not what you want. However this is a way to get the toast to display after 3 seconds and every 3 seconds after for a number of times.
For this we will use recursion because it will make it so that you are not blocked on the main thread.
Call doSomething (the recursive function) from where you need the function to start (remember that the second variable is the number of times you want it to run, and 0 is just required as a counter)
doSomething(0, 3)
create doSomething
private void doSomething(int i, int n) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (i < n) {
Toast.makeText(KeyMapCreator.this, "Try number " + i,Toast.LENGTH_SHORT).show();
actionIWantToDo();
doSomething(i+1, n);
}
}
}, 3000);
}
A Handler just schedules some work for later execution. It doesn't actually block the current thread. All you're doing is scheduling n1 items of work to execute three seconds later, which will all execute in sequence on that exact delay.
You don't really ever want to write code to block the main thread. Ever. It will make your app appear to be unresponsive.

Double (chess like) timer

I am thinking about making an android app to support a game of mine, and I can't find info on how to do it. Here is an app explanation:
The app should have two timers (both set for x minutes). When first player starts his turn (by a button click) his time starts running out. when first player makes his move, he should click his time to stop it, and player two starts his turn.
NOW, the problem I can't find a solution for - When player one takes his turn, time that he loses should pass to the other player's timer.
Example: Both players start with a 5 minute timer. If player one takes 30 second for his turn, his time should go down to 04:30, at which time he clicked on his timer. During that time, for each second he lost, the other player gained time on his timer, so at the beginning of his turn, his time is 05:30. The time goes back and forth, and the player whose timer runs out loses the game.
Any idea how to do this?
I am still stuck to the idea on how to make it, so I have no code to share.
Thank you all for your answers, and effort in helping me, if you have a question I haven't covered, I will gladly answer it.
First, you will need to instantiate class of CountDownTimer everytime you click on button.
For reference check here: https://developer.android.com/reference/android/os/CountDownTimer.html
You have two parameters long millisInFuture, long countDownInterval
Before you start, you will need to create two global variables one for first player, and one for second player like this:
long firstPlayerRemainingTime = 5 * 60 * 1000; // start time 5 minutes
long secondPlayerRemainingTime = 5 * 60 * 1000;
long limitedTime = 30 * 1000; // 30 seconds
CountDownTimer mCountDownTimer;
Now we have came to the most important part and that is logic inside onClickListener method
I don't know if there are two buttons or one, but I will go with two buttons:
btnFirstPlayer.setTag(1); // start timer
btnFirstPlayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (btnFirstPlayer.getTag() == 1) {
startTimer();
} else {
stopTimer();
}
});
private void startTimer() {
long startTime = firstPlayerRemainingTime;
btnFirstPlayer.setTag(2); // stop timer
btnFirstPlayer.setText("Stop");
mCountDownTimer = new CountDownTimer(firstPlayerRemainingTime, 1000) {
public void onTick(long millisUntilFinished) {
firstPlayerRemainingTime = millisUntilFinished;
tvPlayerOneTimer.setText("" + firstPlayerRemainingTime / 1000)
// Here you would like to check if 30 seconds has passed
if ((startTime / 1000) - (limitedTime / 1000)
== (firstPlayerRemainingTime / 1000)) {
stopTimer();
}
// Here you would like to increase the time of the second player
secondPlayerRemainingTime = ++1000;
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
}
}
private void stopTimer() {
btnFirstPlayer.setTag(1);
btnFirstPlayer.setText("Start");
mCountDownTimer.cancel();
// I guess here starts second player move
}
The same logic would go for second player. Let me know if this helped you or if I need to explain anything.

Java Timer.Schedule (infiniti loop) stop running

I have the follow problem:
i'm writing an chat bot in java and i want to call a method even x minutes.
So i read an "Timer.Schedule" is what i need. So i write the following method:
public function timerMethod()
{
int time = 10;
...
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
timerMethod();
}
}, 1000 * 60 * time // 1MSec * 1Sec * xMin
);
}
At the beginning the loop works fine but after a few hours (i think it's after 10-15 hours) the loop dont work anymore...
I dont know why i dont work and dont get any error message :(
Can someone help me pleace???
So you want code to run for x minutes, correct?
If so, convert the time you want the code to run for into milliseconds like this : 1 minute = 60000 ms. There is a method called System.currentTimeMillis(), this will return a value of miliseconds from the EPOCH date (Jan 1, 1970).
You can use a while loop like this:
`
int msTime = 60000; //1 Minute = 60000 MS
int doUntil = ms + System.currentTimeMillis(); //1 minute
while(System.currentTimeMillis() != doUntil)
{
//Code here
System.out.println(¨Hello World¨); //This will print Ḧello World for 60000ms
}
Mmm well first you can stop instantiating multiple times the java.util.Timer() variable. You only need one as an attribute of the class. The timerTask is the only one there that should be reinstantiated.
private Timer timer = new Timer();
Now, surround your code inside the run function with try/catch:
public void run() {
try {
timerMethod();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
Are you calling that timerMethod just once? You can add to this code some prints too in order to check whenever you reschedule your function and when you run your method.

Continuously pass in data to AsyncTask?

In my Android app, I have a snippet of code, similar to Run code for x seconds in Java?
long t= System.currentTimeMillis();
long end = t+15000;
while(System.currentTimeMillis() < end) {
//useful calculation
}
And this code will freeze the UI thread, so I'm wondering if there's a way to continuously pass in data to my AsyncTask that will do the calculation in the background thread to avoid freezing? Or is there a better way, or to keep calling AsyncTask from within my while loop?
For this purpose, use a Handler instead.
It goes like this :
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
//READ HERE WHAT YOU NEED FROM THE SENSOR (useful calculation)
//And then set the next execution of the sensor reading
timerHandler.postDelayed(this, 1000); //runs 1000 milliseconds
}
};
//Launch It for the first time
timerHandler.post(timerRunnable);
//Whenever you would like to stop it, use the following commented line
//timerHandler.removeCallbacks(timerRunnable);

Mp3 player with timer in java [fast forward]

I'm making fast forward button in my Mp3 player. I wrote already code for this, but have problem how to implement timer to jump 5% forward? I mean when I press button timer should jump 5% forward of total long song. This is my fastForward method.
public void FastForward(){
try {
//songTotalLength = fis.available();
fis.skip((long) ((songTotalLength * 0.05)));
} catch (IOException e) {
e.printStackTrace();
}
}
And here is the button method:
private void jButton3ActionPerformed(ActionEvent e) {
mp3.FastForward();
if(mp3.player.isComplete()){
bar = 100;
}
jProgressBar1.setValue((int)bar);
bar+=5;
}
And this one is for timer:
private void setTime(float t) {
int mili = (int) (t / 1000);
int sec = (mili / 1000) % 60;
int min = (mili / 1000) / 60;
start.set(Calendar.MINUTE, 0);
start.set(Calendar.SECOND, 0);
end.set(Calendar.MINUTE, 0 + min);
end.set(Calendar.SECOND, 0 + sec);
timer = new javax.swing.Timer(1000, new TimerListener());
percent = (float)100/(min*60+sec);
}
You're already redundantly tracking progress in two variables fis and bar. For the sake of good design, use one of those to determine elapsed time rather than using yet another variable for the same purpose.
but have problem how to implement timer to jump 5% forward?
You seem to have mistaken the purpose of a Timer. According to the Timer class documentation, it:
Fires one or more ActionEvents at specified intervals.
So the timer is not meant to keep track of how much time has elapsed. It will simply invoke the actionPerformed(ActionEvent) method of your TimerListener once per second (every 1000 milliseconds) as you have it configured.
For a more complete answer, please post the code for your TimerListener class.
Notes
It seems that your setTime(float) method is meant to be called repeatedly, so this method should not be initializing the timer variable. Rather initialize the timer once and leave it alone to do its job.
I'm assuming you intended the supplied float parameter t to represent microseconds.
The float data type has only 7 digits of precision. This could be fine since you're interested only in minutes and seconds, otherwise float is only good for up to about four months of seconds before losing accuracy.
It seems like you wanted your button click handler to do this (increment bar sooner):
private void jButton3ActionPerformed(ActionEvent e) {
mp3.FastForward();
bar+=5; // increment bar before checking complete, and before setting progress
if(mp3.player.isComplete()){
bar = 100;
}
jProgressBar1.setValue((int)bar);
}

Categories