How to set an image with a delay - android

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.

Related

How to use android handler in a loop

I am building my first android application and I am trying to make a memory game. Anyhow, I need to make an array of buttons change color for 1 second and then return to its original color in order, for example: button1 changes to yellow, stays like that for 1 second then returns to gray, then button2 changes to yellow for 1 second then returns, and so on. I tried using the handler but it always works only after the last iteration, this is my code:
for (i = 0; i < 9; i++) {
buttonList.get(i).setBackgroundColor(Color.YELLOW);
runnable =new Runnable(){
#Override
public void run() {
buttonList.get(i).setBackgroundColor(Color.GRAY);
}
};
handler.postDelayed(runnable,1000);}
what am I doing wrong?
EDIT
Found How to do it. First I need to make a runnable class that takes paramaters ex MyRunnable implements Runnable (using Runnable interface), then writing a method that uses this paramater, I can't do it with the regular one because it depends on i and i changes with the iteration.
You need to create a new Runnable inside each loop because all 9 delayed posts are running the same runnable that you create on the 9th and final loop since the loop no doubt takes less than a second to complete. So try something like this:
for (i = 0; i < 9; i++) {
buttonList.get(i).setBackgroundColor(Color.YELLOW);
Runnable runnable = new Runnable(){
#Override
public void run() {
buttonList.get(i).setBackgroundColor(Color.GRAY);
}};
handler.postDelayed(runnable,1000);
}
You're synchronously (at the same time) setting all buttons' colors to yellow, and also creating 9 asynchronous tasks (one for each button) to change color to gray after one second. It means all buttons will change colors back to gray after around 1 second, (more or less) at the same time.
Think of the handler as a queue that you add tasks to. The call postDelayed() is scheduling your tasks to be executed in the future, but all of them are scheduled at the same time, so all of them will be executed at the same time in the future.
I haven't run it, but I think this approach is more of what you are looking for:
// Those are fields
private int buttonIndex = 0;
private boolean yellow = false;
private final Handler handler = new Handler(new Handler.Callback() {
#Override
public void handleMessage(Message msg) {
if (!yellow) {
buttonList.get(buttonIndex).setBackgroundColor(Color.YELLOW);
handler.sendEmptyMessageDelayed(0, 1000);
} else {
buttonList.get(buttonIndex).setBackgroundColor(Color.GRAY);
if (++buttonIndex < 9) handler.sendEmptyMessage(0);
}
yellow = !yellow;
}});
// Call this to start the sequence.
handler.sendEmptyMessage(0);
Note that I'm using sendEmptyMessage*() instead of post*(), but either approach could be used. Additionally, handler's messages (tasks) can have input parameters, so it'd be nice to use them.

How to wait button clicks for a while in android

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

Android postDelayed does not delay

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.

Small android animation delay issue

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'.)

Pausing with handler and postDelayed in android

I'm very new to android programming so please forgive my noobie-ness. I'm trying to create a very simple activity that will have one TextView in the middle of the Layout and just have it switch to a different text every couple of seconds. For example, the TextView will say "text1", pause for a couple of seconds, then say "text2, and pause again. Eventually, I want to add more texts and have them all cycle one after another. I know this seems like a super simple thing but I'm mainly trying to learn about threads and handlers at this moment. Anyways, I've read up on how we should keep lengthy things off the UI thread to prevent an error so I thought I'd use a handler to simply switch between 2 texts on screen. Unfortunately, I can't get this to work. Here's some code:
public class MainActivity extends Activity {
String[] myarray = {"text1" , "text2"};
int arraylength = myarray.length;
int count;
Handler handler = new Handler();
TextView mytexts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mytexts = (TextView)findViewById(R.id.my_texts);
mytexts.setText(myarray[0]);
Thread t = new Thread( new Runnable(){
public void run() {
for (int count = 0; count < arraylength; count++){
handler.postDelayed(new Runnable(){
public void run() {
mytexts.setText(myarray[1]);
}
}, 7000);
}
}
});
t.start();
}
}
From what I can see in the logcat, the handler seems to run postDelayed one right after another (in my code's case, it does NOT wait 7 seconds with the postDelay to do another postDelayed). Also, I would like to make the 1 in "mytexts.setText(myarray[1]);" be the same as "count" in the for loop so it can be the same as one of the strings in the array but that gives me an error. I've been stuck on this for hours and other examples I've found online seem way too complicated for someone like me who mainly wants to get the basics down before I can tackle other things. Any help at all with any of this would be much appreciated. Thank you.
postDelayed is non blocking, meaning it would add it to a queue of I'll do this later. So what you are probably seeing is all text updates happening together at the 7th second. I say this because you are postDelaying from the onCreate method when in reality you probably want to do it from onResume or even onPostResume.
Also there is no reason to create a thread to add runnables to the post queue. Your code should look more like this:
(Note the time to delay multiplier)
#Override
protected void onResume() {
super.onResume();
for (int count = 0; count < arraylength; count++){
handler.postDelayed(new Runnable(){
#Override
public void run() {
mytexts.setText(myarray[count]);
}
}, 7000 * (count + 1));
}
}
This is because your loop is setting all your handlers to run after 7 seconds not 7 seconds after each other but but after 7 seconds from now. You can either add in the postDelayed method or use the postAtTime method in handler .
Also, you don't need to do this in a thread, you can get rid of that altogether.

Categories

Resources