I just want to call a function after every 3secs on click of a button
What is going wrong here-
galleryBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Handler handler = new Handler();
for(int i = 0;i<3;i++){
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 5s = 5000ms
viewAnimator.showNext();
}
}, 3000);
}
}
});
You don't actually say what goes wrong but I'll take a wild guess that nothing happens (i.e. no animations) and the reason for that is probably that your Handler is being GC'd long before it gets to handle anything. Try keeping moving 'handlers' scope from local variable to class member.
(Also note that, even when it works, all 3 of your functions will run at more or less the same time. If you want them to run 3 seconds apart you should change the '3000' to 'i*3000'.)
Related
I am developing an application for blinds.
I have 4 screen sized buttons (overlapped). Every step of program one button will be clickable and every button has more than one job.
My program starts with a voice (Android TTS engine). Like "please touch screen to do x". After this step I want to wait 3 seconds for button click, if button is not clicked vocalize "please touch screen to do y" and wait 3 seconds again for job y. (x and y is first button's jobs).
Button should do one of them according to touching screen. But how can I wait 3 seconds for button click and continue to vocalize next options and wait 3 seconds again.
If first button is clicked, it will disappear-button 2 will be clickable- and TTS engine will start to vocalize second buttons options. Application will be work like this but I am stuck in waiting button clicks part.
I would advise you to use android.os.Handler instead. In your case you could do something like this:
public void onCreate() {
this.handler = new Handler()
playTheVoiceOfThingX()
viewToTap.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
doThingX();
}
});
handler.postDelayed(new PrepareThingYTask(), 3000);
}
class PrepareThingYTask() implements Runnable {
viewToTap.setOnClickListener(new OnClickListener(){
#Override
public void onClick() {
doThingY();
}
});
handler.postDelayed(new PrepareThingZTask(), 3000);
}
class PrepareThingZTask() implements Runnable {
....
}
A good reminder, the runnable executed by the handler can be executed in UIThread, so no heavy work on it, or create a different looper to run it.
Regards
You could solve your problem with busy wait.
So after you first vocalized "please touch screen..." you would start a background thread which waits for a specific amount of time, like so:
new Thread(new Runnable() {
public void run() {
Thread.sleep(3000);
runOnUiThread(new Runnable() {
#Override
public void run() {
//vocalize
}
});
}
}).start();
As you can see, from within the thread a new runnable is started after 3 seconds which again runs on the UI Thread. This, because I think I remember that you should make such sound-things (depending on your method of how to play the file / sound) only from the UI Thread.
However, this is just an idea and I could not test-run my code!
But I hope I inspired you!
Regards
Me
I have the Problem that my Android app does not delay a second (or 10 seconds), if I use the postDelayed method..
Basically I would like my program to wait one second after I clicked the button, then update the text on my textview ("READY"), wait another 2 seconds, then update the textview again ("SET") and then it should start another activity (not yet implemented :-) ).
With my code, the programm starts and after I click the button the textview shows the last text ("SET") immediately.. It just does not wait.
What am i doing wrong?
Here is my code:
public class MyCounterActivity extends Activity {
private long mInternval = 100000;
private Handler mHandler;
private Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
//updateInterval(); //change interval
startRepeatingTask();
}
};
void startRepeatingTask(){
mHandler.postDelayed(mStatusChecker, mInternval);
//mStatusChecker.run();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gym_counter);
final TextView tv1 = (TextView) findViewById(R.id.fullscreen_content);
final Button startButton = (Button) findViewById(R.id.startbutton);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final long up;
EditText textUp = (EditText) findViewById(R.id.editTextUp);
up = Integer.parseInt(textUp.getText().toString());
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//
}
},1000);
Log.d("after 1 runnable", "whaaat");
tv1.setText("Ready");
handler.postDelayed(new Runnable() {
#Override
public void run() {
//
}
}, 2000);
Log.d("after 2nd runnable", "whaaat 2");
//startRepeatingTask();
tv1.setText("SET");
}
});
}
I also tried to run it with the runOnUiThread() (within the onClick(View v) but with with the same result). I expected it to wait 1 second (startRepeatingTask()) and then runs the loop and waits several seconds...
runOnUiThread(new Runnable() {
#Override
public void run() {
startRepeatingTask();
for (int u = 0; u < up; u++){
startRepeatingTask();
}
}
}
});
Hope my description makes sense :-).
Thank you for your help!
EDIT:
I was now able to find a solution for my first problem. The answer from #mad in this post helpded me: How to start a different activity with some delay after pressing a button in android?
(Thats probably the same thing that #laalto tried to tell me. Thanks for the hint!)
In the onClick()
tv1.setText("READY");
mHandler.postDelayed(mDelay1, 2000);
And then the Runnable
private Runnable mDelay1 = new Runnable() {
#Override
public void run() {
if (tv1.getText()=="READY")
tv1.setText("SET");
}
};
BUT:
If i want to refresh the text on my Textview after every second, how do i do that? I cant just call mHandler.postDelayed() several times.. Any help is appreciated.
When you call postDelayed(), it just places the Runnable in a queue and returns immediately. It does not wait for the runnable to be executed.
If you need something to happen after a delay, put the code in the run() method of the runnable.
Whenever you call something like Thread.start(), handler.postDelayed, view.postDelayed, AsynchTask, TimerTask .. you enter the world of threading or you might call it parallel computing.
So there can be multiple threads ("codes") running at the same time.
When you are inside your Activity it is running in a Thread that is calld UI-thread or main thread. All graphics is handled in that thread and that thread alone.
Do NEVER wait in the UI-thread!
Example: you have a button that switches color from say gray to yellow on pressing it. Now you enter a Thread.sleep(10000); - waiting 10 seconds at the start of your onClick.
You will then see that the button stays yellow (=pressed) for 10 seconds even if you only pressed very shortly. Also: if you overdo it android os will become angry and post the user if he wants to force-close your app.
So what happens on handler.postDelayed?
Android will very quickly open a thread that runs in the background parallel to your UI thread. So in some nanoseconds it has done that and will execute the next command in UI thread (in the example above it is Log.d). In the background it will wait and count the millis until time is up. Then any code that is inside the runnable.run method will again be executed in the ui-thread after the wait.
Note also: postDelayed will not be super precise with the wait time as usually the ui-thread is quite buisy and when the wait time is up it may have something else to do. Your runnable code will be added to a queue and executed when ui-thread is ready again. All this happens without you having anything to do about it.
Also:
Remember to work with try/catch inside the runnable.run as many things can happen while waiting - for example user could press Home button closing your app - so the ui-element you wanted to change after the wait could already been destroyed.
Is there any function in Android that can use to make the activity wait for an interval and continue working?
I mean , for example, I use setContentView() to set a layout , and after 3 seconds it will load another layout, and continue to do another job, I don't need to repeat doing same thing after an interval, just continue do another thing.
Thanks in advanced.
You can Use Following Method to Set Interval
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
// Do your code here
}
}, 3000);
Here, 1000 = 1 Second
But Before running this code make sure that you are not in BACKGROUND PROCESS THREAD...otherwise this may cause an error..
Do it at Android Style:
Handler mHandler = new Handler();
mHandler.postDelayed(runnableHandler, 3000);
private Runnable runnableHandler = new Runnable() {
#Override
public void run() {
doSomething()
}
};
private void doSomething() {
// Before do something remove all callbacks from Handler
mHandler.removeCallbacks(runnableHandler);
andFinallyDoWhatYouNeed();
}
Okay so I have a rather weird problem here:
I have one method calling a sequence of delayed methods, for example:
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
flash(true, 3000);
flash(false, 1200);
}
});
And the flash function goes:
private void flash(final boolean color, int duration) {
// SLEEP duration MILLISECONDS HERE ...
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
changeColour(color);
}
}, duration);
}
What happens is that the 1200 ms timer kicks off before the 3000 ms timer although the 3 second one should go first. I tried adding a trigger for the timers but that only freezes the whole app:
...
public void onClick(View view) {
flash(true, 3000);
while(wait); //stop here until the timer triggers wait to false
wait = false;
flash(false, 1200);
}
...
public void run() {
changeColour(color);
wait=false;
}
...
Any help is appreciated, thank you.
What happens is that the 1200 ms timer kicks off before the 3000 ms
timer although the 3 second one should go first.
The first should trigger first only if you set the exact time interval on both of them. However, right now you just trigger two flashes, one to be run after 3 seconds and one after 1,5 seconds(from the current time).
In order to do what you want you need to take in consideration the time of the first trigger when posting the second message:
flash(true, 3000); // post a message after 3 seconds
flash(false, 4200); // post a message after 4,2 seconds(so at 1,2 seconds after the first flash runs)
I have an "Activity" with three images. When one image is clicked, all the images are to switch to another picture. Is there a way to make the switches such that there is a 2 second delay before the images actually change (i.e. a 2 second delay in every 'for loop' below)? I am trying to do this with a timer but it does not actually to the delay when I run my program:
protected void onCreate(Bundle savedInstanceState) {
image1.setOnClickListener(this);
#Override
public void onClick(View arg0)
{
do_switches();
}
private void do_switches()
{
//loop through all images and change them
for(int j=1 ;j<=3; j++)
{
final int curr2=current;
final Handler handler = new Handler();
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
switch(curr2){
case 1:
image1.setImageResource(ImageArray[1]);
break;
case 2:
image2.setImageResource(ImageArray[2]);
break;
case 3:
image3.setImageResource(ImageArray[3]);
break;
}
}
});
}
}, 2000);
}
}
I have also tried using just SystemClock.sleep(2000) instead of the timer but I that didnt work either.I also tried setting up a Thread with a try/catch with no luck or maybe I didn't implement it properly. Is there a way to put this delay on every iteration of my for loop?
Thanks
Not one of best option, but still you can try CountDownTimer.
http://developer.android.com/reference/android/os/CountDownTimer.html
You can use handler.postDelayed(Runnable r, long timeInMillis). Make your runnable that changes the pictures and then call postDelayed() and pass in the runnable and 2000 for the time delay.
Edit: Ahh I see what you are trying to do. As far as I know you aren't going to be able to make a for loop pause for 2 seconds each time through. You can get the same effect though if you chain the postDelayed() calls. Just set up the next runnable and call postDelayed() on it inside the first one, and same for the third one from inside the second one. You will end up with the same functionality as a for loop that pauses for 2 seconds each iteration.