Random Countdown timer - android

I am pretty new on programing, and I am having a hard time trying to figure out how to make a random countdowntimer. This random countdowntimer was supposed to execute an object after the time (between 3-10 sec) has reached zero.And I really donĀ“t know how to do that. Could someone please give me some examples on how I maybe could solve this problem.
Thanks!

countDownTimer = new CountDownTimer(random value, tick value) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
}
}
};
you can put random value as a value 3-10 its means onFinish called after this time
to create random value use code below
Random r = new Random();
int randomInt = r.nextInt(10 - 3) + 3;

int time = new Random().nextInt(8) + 3;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// execute yor code
}
},time * 1000);
Use this. Hope help you.

Related

can not run countdowntimer at all

I have a problem with countdown timer.I try some of solutions and articles in this site but they never worked for me. so, please read my codes...
also I used
handler.postDelayed(new Runnable() {
before and it was not my solution but it just worked correctly.
Main question is:
I want to do something like below:
(button pressed)
do some codes1
delay1
do other codes2
delay2
go back to *do some codes1* again.
In short, this is my real code:
itimesec--;
setdelay();
irepeat--;
setrelax();
and this is in my functions:
public void setrelax(){
CountDownTimer yourCountDownTimer1 = new CountDownTimer(50000, 1000) {
public void onTick(long millisUntilFinished1) {
itotalsnozee--;
TextToSpeechFunction(" "+itotalsnozee);
}
public void onFinish() {
itotalsnozee=fitotalsnozee;
isrelax=false;
TextToSpeechFunction("do again");
}
}.start();
yourCountDownTimer1.cancel();
}
I tried to use a variable insted of 50000 but it was not useful anyway.
I tried to put setrelax funtion codes directly into oncreate but it never worked.
it just jumped to
}.start();
yourCountDownTimer1.cancel();
every times and go out.
I tried all the codes without any delay function and they runned correctly.
what is my wrong please...
You need to remember that your code won't be executed sequentially when using the CountDownTimer because it's working asynchronously (via Handler).
Let's dissect your code. Your following code here:
public void setrelax(){
// 1. Creating CountDownTimer
CountDownTimer yourCountDownTimer1 = new CountDownTimer(50000, 1000) {
public void onTick(long millisUntilFinished1) {
// 2. onTick called
...
}
public void onFinish() {
// 3. onFinish called
...
}
}.start();
// 4. CountDownTimer is cancelled.
yourCountDownTimer1.cancel();
}
will be running in the following sequences:
Creating CountDownTimer
CountDownTimer is cancelled.
onTick called 49 times repeatedly (50000/1000 = 50 - 1 ).
onFinish called
So, change your algorithm to something like this:
do some codes1
delay1
--> When delay finished, do other codes2. Then do delay2
You need to call the next code in the CountDownTimer.onFinish()
I looked at your code and I could not find any big mistakes but try this instead
Instead of
.start();
use
yourCountDownTimer1.start();
and remove yourCountTimer1.cancel();
like this :
public void setrelax(){
CountDownTimer yourCountDownTimer1 = new CountDownTimer(50000, 1000) {
public void onTick(long millisUntilFinished1) {
itotalsnozee--;
TextToSpeechFunction(" "+itotalsnozee);
}
public void onFinish() {
itotalsnozee=fitotalsnozee;
isrelax=false;
TextToSpeechFunction("do again");
}
};yourCountDownTimer1.start();
}
Hope it helps.
below is the code for running otp timer in our code.you can copy paste i have mentioned the comments please follow the same.
CountDownTimer countDownTimer; //define countDownTimer
countDownTimer.start(); // start countdown timer on some event like on click
String x="Your code will expire In";
String y="mins";
counttimer(); call the method counttimer which includes all the code of timer
public void counttimer(){
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
String text = String.format(Locale.getDefault(), x+" %02d : %02d "+y,
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % 60);
phonever_timer.setText(text); //set timer into textview object
}
public void onFinish() {
phonever_timer.setText("Otp Expired..!");
}
};

kill an Activity after a certain time

Im working on a Quiz App. in which I have a different types of quizzes. Quiz with Time and Quiz without Time. Quiz without time is simple and there is no certain or specific time given to attempt the quiz. But the Quiz with Time is time restricted Quiz.
What I Want:
When an individual try to attempt a time restricted quiz. The certain amount of time will be show on an activity for instance remaining time (30 min left). and after the 30th min the activity automatically stop. I have tried timer class but that is used for delay.
how can I stop a activity after a certain time?
Thanks in Advance
public void countDown() {
new CountDownTimer(60000*30, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000) % 60 ;
int minutes = (int) ((millisUntilFinished / (1000*60)) % 60);
int hours = (int) ((millisUntilFinished / (1000*60*60)) % 24);
String my_new_str =((((((((( (pad(hours)+":"+pad(minutes)+":"+pad(seconds)));
timer.setText( my_new_str);
float pvalue = ( float)(millisUntilFinished*100)/(60000*30);
myprogressbar.setProgress((int)(Math.round(pvalue)));
}
public void onFinish() {
timer.setText("Completed");
goToResult();
this,finish();
}
}.start();
}
you can do this using Handlers
try some thing like this...
Handler handler = new Handler();
Runnable x=new Runnable() {
#Override
public void run() {
finish();
}
};
handler.postDelayed(x, 6000);
Put your question in Thread...
Thread t=new Thread()
{
public void run()
{
try{
sleep(30000);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
Intent intent = new Intent(Splash.this, Login.class);
startActivity(intent);
finish();
}
}
};
t.start();
Try to use AsyncTask or Handler in your Activity. i think you set some certain time limits for the
Quiz Question so please make sure to use any one of this above i mentioned.
Handler handler = new Handler();
Runnable x=new Runnable() {
#Override
public void run() {
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
startActivity(intent);
finish();// activity will kill. or use
System.Exit();
}
};
handler.postDelayed(x, yourtimelimit(in timemills or millisecond));
Even you doesn't work yet means try to use onComplete listener and the put it finish in that method or
use onDestroy method inside to finish().
thank you

Android Creating a variable that increments once per second

In Java for Android, I want to create a variable that increases by 1 every second, in other words, it counts, that way I can check to see if a function has been called in the past 3 seconds, and if not, I want it to do something different than if it had been.
Is there any built-in way to do this? I'm familiar with the Timer class, but it doesn't seem to work the way I would want it to.. is there anything else?
tl;dr: I want to create a variable that increases by 1 every second, so I can use it to treat a function differently based on how long it has been since its last call. Is there an easy way to do this? If not, what is the hard way to do this?
Why not store the last time the method was called instead, then check it against the current time?
private long timeLastCalled;
public void someMethod() {
timeLastCalled = SystemClock.elapsedRealTime();
}
public boolean someMethodCalledRecently() {
return (SystemClock.elapsedRealTime() - timeLastCalled) > 3000;
}
final int[] yourVariable = new int[1];
yourVariable[0] = 0;
updateVariableTimer = new CountDownTimer(howLongYouWantTimerToLast, 1000) {
#Override
public void onTick(long l) {
yourVariable[0] += 1;
}
}.start();
Or Alternatively to do it with a flag instead of keeping track of variable counting:
final boolean functionCalledRecently = false;
hasFunctionBeenCalledRecentlyTimer = new CountDownTimer(3000, 1000) {
#Override
public void onTick(long l) {
functionCalledRecently = true;
}
#Override
public void onFinish() {
functionCalledRecently = false;
}
}.start();
If you just need to see if the method has been called within the last 3 seconds you can use a Handler and a Boolean flag to acomplish this.
private Handler mHandler = new Handler();
private boolean wasRun = false;
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if(wasRun){
//whatever you want to do if run
}
mHandler.postDelayed(this, 3000);
}
},3000); //3 sec
In this example the Handler will run on a 3 second delay. Each time it runs it will check to see if the other method was perviously called by evaluating if(wasRun). This way you can change what happens if the method was/was not called. The handler will then start iself again on another 3 second delay. All you have to do then is update the wasRun flag to be true if your method was called, or false if it was not. .

Method to return an array

In my android project, I have a countdown that randomizes a boolean for an array. The problem is, every time it ticks it always creates the array and the for loop. Can someone help me how to import my codes on a seperate class and method? I just want to call the returned value of an array in my countdown while it loops on a separate class. Please help me, TIA! :)
This is my countdown inside my onCreate():
new CountDownTimer(300000, 1000) {
public void onTick(long msUntilFinished) {
txtCounter.setText("" + msUntilFinished/1000);
ImageView[] pic= {img1, img2, img3, img4, img5};
Random aRandom = new Random();
for (int i=0;i<12;i++){
arrays[i] = aRandom.nextBoolean();
if(arrays[i]){
pic[i].setImageResource(R.drawable.show);
appear = true;
} else {
pic[i].setImageResource(R.drawable.hide);
appear = false;
}
}
} // end of onTick
public void onFinish() {
txtCounter.setText("done!");
}
}.start();
If you don't want the array to be created each time it ticks just place the array initialization outside of the thread like this:
for (int i=0;i<12;i++){ arrays[i] = aRandom.nextBoolean();}
new CountDownTimer(300000, 1000)
{
...
}.start();
Important: "arrays" has to be final. If you cannot do this then you have to do:
for (int i=0;i<12;i++){ arrays[i] = aRandom.nextBoolean();}
final SomeClass[] finalArray = arrays;
new CountDownTimer(300000, 1000)
{
...
if(finalArray[i]) ...
...
}.start();

Showing Timer in android

My objective is to display a simple timer clock on my screen where it starts from 20 and goes on decreasing and when it becomes 0 I want to start an action.
How to achieve this ?
Thanks in advance
I don't know how you want to display it but you can do this also just by taking a TextView and keep changing its Text every second.
static int i = 20;
new CountdownTimer(20000, 1000) {
public void onTick(long millisUntilFinished) {
i = i-1;
mTextField.setText(String.valuOf(i));
}
public void onFinish() {
//do your stuff here
}
}.start();

Categories

Resources