I need help with writing a code,
How do I make a code to wait until the countdown timer is finished?
I tried with boolean says if countdown timer is running and in the code, it was like this:
---part 1 of code---
While(running){}
---part2 of the code---
It makes the screen freeze... Idk how to solve this.. help someone?
CountDownTimer already has that, You just need to put the codes that you want to make them work after the timer finished, inside the onFinish(), like below
countDownTimer = new CountDownTimer(10000, 1000) {
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
//this part will work after timer have finished
}
}.start();
Related
I have this code in android studio:
The question is that if I give the button back and the main activity takes me, that is going to continue executing.
How do I make it so that once it's behind, it does not run what's in the onfinished?
new CountDownTimer (40000,1000) {
#Override
public void onTick(long l)
{
crono.setText("00:"+l/1000);
if(contador==10)
{
}
}
#Override
public void onFinish()
{
if(value.equals("tiempo"))
{
crono.setText("00:00");
}
else
{
esperar();
}
}
}.start();
CountDownTimer class help us to implement timer with custom time interval and duration. It provide 2 callback onTick(int millisUntilFinished) which called after each interval and onFinish is called when time duration is completed.
If you want to stop countdown then store instance countdown and call countdown.cancel() in onDestroy or button click(any where by user action)
You can refer this
I'm new here and noob as well. I started learning Java and Android by making my first simple app.
I want to do the time loop to do some function every 1 sec.
I have this:
new Timer().scheduleAtFixedRate(new TimerTask(){
#Override
public void run(){
imV.setImageResource(stageArray.getResourceId(step, -1));
Log.d("MyApp","I am here");
step ++;
}
},0,1000);
It's in my init() function.
After I run this on my device, the app crashes.
When I delete the imV.setImageRes... line it runs, but I don't get log notifications.
The step value is changing.
Something similiar is happening when I use a Handler.
So why my app crash?
Why cannot I see any log.d from this loop?
Are there better ways to do time loop to make simple changes?
Your app has crashed because you access the Android UI toolkit from outside the UI thread when you call imV.setImageResource(stageArray.getResourceId(step, -1));. So that, exception has occurred. You must set image for imageview in UI thread:
runOnUiThread(new Runnable() {
#Override
public void run() {
imV.setImageResource(stageArray.getResourceId(step, -1));
}
});
Or simple solution with CountDownTimer
new CountDownTimer(totalStep * 1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
step = millisUntilFinished/1000;
imV.setImageResource(_yourResID);
}
#Override
public void onFinish() {
Log.d("Finish", "Done");
}
}.start();
I recently began working with Java and am exploring Android development. I was trying to port over one of the Java programs I made, but I am having some difficulty with getting the java Timer to function the same way in Android. I read through a number of posts and they, for the most part, indicated that it would be better to use the Handler class in android as opposed to Timer.
This was my timer in Java:
playTimer = new Timer(1000/model.getFPS(), new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// do something
...
if( finished everything ) playTimer.stop();
}
});
And once a certain button was clicked, I would simply run "playTimer.start()" to start it.
As you can see, I had it set up so that the user could set the FPS they wanted (by simply setting the first parameter of the Timer class to 1000/model.getFPS()).
Now I've tried to do something similar in Android using handlers, but I am having some difficulty. It appears that the Handler ticks are not firing at the proper intervals. It seems that they are quite slow compared to what I need it to be. This is what I did in android so far:
public void startTimer() {
playHandler = new Handler();
startTime = System.currentTimeMillis();
playHandler.removeCallbacks(updateTimeTask);
playHandler.postDelayed(updateTimeTask, 0);
}
private Runnable updateTimeTask = new Runnable() {
public void run() {
// do something
...
if( finished everything ) playHander.cancel();
else {
playHandler.postDelayed(updateTimeTask, 1000/model.getFPS());
}
}
};
Excuse the semi-pseudocode. Can anyone shed any light? Thanks guys.
You can use a timer as below. The timer runs every second incrementing the counter. Displs the counter value in textview.
Timer runs on a different thread. SO you should set the text on the UI Thread.
The counter runs from 0 to 99. After 99 the timer is cancelled. Also cancel the timer when not required like in onPause().
public class MainActivity extends Activity {
TextView _tv,tv2;
Timer _t;
int _count=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_tv = (TextView) findViewById( R.id.textView1 );
_t = new Timer();
_tv.setText(R.string.app_name);
_t.scheduleAtFixedRate( new TimerTask() {
#Override
public void run() {
_count++;
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
_tv.setText(""+_count);
if(_count==99)
{
_t.cancel();
}
}
});
}
}, 1000, 1000 ); //change this value of 1000 to whatever you need.
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
_t.cancel();
}
}
If you decide not to use Timer (for whatever reason) you can just write a separate Thread that sleeps for x milliseconds and then wakes up and calls whatever Runnable you want it to call. That's going to be pretty precise. I have it working at the 10 millisecond level and it works quite nicely.
Just remember that it HAS to call a Runnable because a separate Thread can't have direct effect on anything on the main display thread.
public boolean keepPlayingAnimation = true
Handler h = new Handler()
Runnable updateDisplay = new Runnable(){
public void run(){
//do something in my display;
}
}
new Thread(){
public void run(){
while(keepPlayingAnimation){
try{
sleep(10);
}catch(Exception e){
}
h.post(updateDisplay);
}
}
}.start();
Just don't forget to set keepPlayingAnimation to false when you're done with this cause otherwise it will sit there running in the background for ever (or just about).
Take a look at Android Timer
It already has everything you need i guess. From ticking every 1 second to finish handly and so on.
Here is an example how to setup an TimerTask: setup
Not sure if you need such but i just remembered that i made this.
I want to send a notification after 5 seconds.
I found this code example to do something after 5 seconds, but I just can set a Log.e().
The Notification method is also working. But if I want to call the method setNotification(), I get a RuntimeError after 5 seconds:
Can't create Handler inside Thread that has not called looper.prepare().
I found very much help, but nothing works. So I hope you can help me.
public class Reminder {
Timer timer;
public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds * 1000);
}
}
class RemindTask extends TimerTask {
public void run() {
todo_list rem = new todo_list();
rem.setNotification("Todo!", false, 1);
}
}
public class todo_list extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
new Reminder(5);
}
public void setNotification(String text, boolean ongoing, int id) {}
}
You need to call rem.setNotification from a thread which will keep running always. One way is to use runonuithread
runonUithread(new Runnable(){
run(){
rem.setNotification("Todo!",false,1);
}
});
You'll get this error when you execute some code that shouldn't be done in another thread than the UI thread. So simple get an activity object and call runOnUiThread(Runnable action) {} on it. Place that code that generates the error in the Runnable.
I hope this helps.
Just testing out a simple block of code in my mainActivity's onCreate:
Timer timer2 = new Timer();
TimerTask testing = new TimerTask() {
public void run() {
Toast.makeText(mainActivity.this, "test", Toast.LENGTH_SHORT).show();
}
};
timer2.schedule(testing, 1000);
I get the "force close" error though.
What gives?
Alright for anyone else who runs into this, I fixed the problem by using a Handler and Runnable to do the Toast, which seems to be needed for UI interaction:
final Handler handler = new Handler();
Timer timer2 = new Timer();
TimerTask testing = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Toast.makeText(mainActivity.this, "test", Toast.LENGTH_SHORT).show();
}
});
}
};
timer2.schedule(testing, 1000);
I still don't understand why this is necessary though, perhaps someone could explain? But hey at least this code works lol.
Timer(Tasks) are bad! Do it the Android way: Use a Handler.
As you can see in the code snippet, it’s pretty easy to go that way too:
First we need a Handler that starts the Runnable after 100ms
private Handler handler = new Handler();
handler.postDelayed(runnable, 100);
And we also need the Runnable for the Handler
private Runnable runnable = new Runnable() {
#Override
public void run() {
/* do what you need to do */
foobar();
/* and here comes the "trick" */
handler.postDelayed(this, 100);
}
};
So the “trick” is to tell the handler at the end to start the Runnable again. This way the runnable is started every 100ms, like a scheduleAtFixedRate() TimerTask! If you want it to stop, you can just call handler.removeCallback(runnable) and it won’t start again, until you tell it to
This exact issue is discussed in this article:
http://developer.android.com/resources/articles/timed-ui-updates.html
The app crashes because you are attempting to access elements of the UI thread (a toast) from a different thread (the timer thread). You cannot do this!
You can get round it by either:
Sending a handler message from the timer thread to the UI thread, and then showing the toast in the UI handler function.
OR
In the timer code run use 'runOnUiThread':
#Override
public void run()
{
mainActivity.runOnUiThread(new Runnable() {
public void run() {
// Access/update UI here
Toast.makeText(mainActivity.this, "test", Toast.LENGTH_SHORT).show();
}
});
}
#YoungMoney
It works but only the first time... Did you make it display the Toast message every second??
Mine only worked once...
===
Edit:
Just realised your last line of code is missing the last value which is how often to repeat.
For anyone else concerned, change this:
timer2.schedule(testing, 1000);
to this:
timer2.schedule(testing, 1000, 2000);
If you want to start the timer in 1 second, and update every 2 seconds.
TimerTask task = new TimerTask() {
#Override
public void run() {
//do something
}
};
Timer t = new Timer();
t.schedule(task, 2000);