Programmatically 'press' button every 60 seconds - android

In my app, I've been asked to add an auto update function. What I'm trying to do is have a timer event so that if the user hasn't pressed the update button in the last 60 seconds, do a 'refreshButton.performClick();'.
I've been searching but I can't find an example where the timer interacts with the UI. I keep getting errors like 'only the original thread that created a view hierarchy'.
If the user does press the button, I want to reset the timer.
Is this even possible?

You only can interact with aView from the UI thread.
You can make something like this in your timer task;
Define this variable in your class:
Handler handler = new Handler();
In your timer task call:
handler.post(new Runnable(){
public void run(){
refreshButton.performClick();
}
});

I think you are going in the wrong direction. Instead of trying to press the button, just set a timer to call the same method that is called once the button is pressed, it will make it way simpler, and will not involve the UI for no reason.

You can use AlaramManager class and a background service to run your code on every 60 second.
Here is an example see AlarmService_Service.java

Related

sleep in android doesn't work

Well I just want to press a button and a countdown appears in it however when I press the button the program stops and finally shows the number 1 but doesn't show 3 or 2.
btnTurno.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
btnTurno.setText("3");
SystemClock.sleep(1000);
btnTurno.setText("2");
SystemClock.sleep(1000);
btnTurno.setText("1");
}
});
What I'm doing wrong?
First of all, Sleep should be called as Thread.sleep(x);
But on the other hand , sleep is NOT recommended since it will block the user interaction with the application.
If you want to make a countdown ( as it looks like what you are doing ), you should look at this
http://developer.android.com/reference/android/os/CountDownTimer.html
onClick is being executed in single handler message on GUI thread, so each time you change text, it overwrites previous value, so system is not able to redraw view.
Also you should not call sleep() on main gui thread, that will cause ANR - application is notresponding
Setting the text and drawing the text are separate operations that both happen on the same thread. You're setting the text three times before the framework gets the chance to draw anything, so all you see is the last change.
For this to work, you'd need to do your text updates and sleeps on a separate thread. However, you can't make UI calls directly on a different thread, so you need to post your messages.
One approach would be to create an AsyncTask, and use your code above but call publishProgress() where you're currently calling setText(). The publishProgress() call in the async thread results in onProgressUpdate() running in the UI thread; from there, you can call setText() to update the UI.
Edit: the CountDownTimer approach mentioned in a different answer is better.

How to set timer when acitivity changes?

Actually i just want to know whether can we set timer when the activity changes.
Detail description:
startActivity(new Intent(this,Second.class));
I know that by using this code we can change one activity to another activity. By the above code when the activity is changing it changes quickly as know to everyone, but what i want is in button click event when i write this code, when i click that button the same activity needs to be on screen for some particular time (i.e., around 10 seconds) & after that it needs to change activity. I thought of keeping timer here but i didn't got any idea how to do that.
Can anyone please help me with this.
The easiest thing would be to simply create a Handler and post a message to it 10 seconds later.
Handler activityChanger = new Handler();
activityChanger.postDelayed(new Runnable(){
startActivity(new Intent(this,Second.class));
}, 10000);
Put that where you normally create your activity within the scope of startActivity. You're current activity should run for 10 more seconds and the new one starts up.

Best way to execute a thread after a period of time in android

I am having a service in my application that puts a runnable (in another java file) in a thread and starts it.
That is working fine for once, but i want it to be repetitive due to a certain period.
I need a good way to handle that.
Reason why I didn't use the answers to other questions is that I don't want it to repeat infinity nor I know how many times it'll repeat the task. It'll simply stop due to a button click in the UI.
I was thinking of using a loop with a sleep and if statement. But I think that's really bad design for my application. Is there a standard way for doing such thing?
Thanks...
You can use a handler that somehow acts like a timer but I think it is better for your situation.
You initialize it like this:
Handler delayhandler = new Handler();
Set the time it fires like this (in ms):
delayhandler.postDelayed(mUpdateTimeTask, 500);
And it calls this:
private Runnable mUpdateTimeTask = new Runnable()
{ public void run()
{ // Todo
// This line is necessary for the next call
delayhandler.postDelayed(this, 100);
}
}
You can also remove the next call with:
delayhandler.removeCallbacks(mUpdateTimeTask);
Use a TimerTask and have it execute your thread/method.
http://android.okhelp.cz/timer-simple-timertask-java-android-example/
http://developer.android.com/reference/java/util/TimerTask.html - You can use the Cancel() method to stop the TimerTask from executing.
Use the Timer it will run the thread after a given time period and when you want to stop just stop timer or set it to infinite time period.

Changing button background dynamically in thread in Android

I'm developing my first app for Android and its supposed to be a game. Everything is fine but there's one thing I just can't wrap my head around.
In my game's "main" activity (not the first activity which starts when the app starts) I want to have a method which starts a thread which changes a buttons background color/image (go with color because I haven't made any images just yet) for one second then turns it back. I wan't the method to also have an integer parameter which makes it perform this n times. I want to be able to call like changeButtons(5); and it turns button x background blue for 1 second then waits 1 second five times.
So practically I'm trying to make a "main" thread which runs during the game and inside that thread I'm going to run this method whenever certain conditions are true (a thread which calls a thread).
So I have 2 questions. The first one is "Is this possible? " and If so can someone show me how to do it (not all of it of course but help me get started at least)? Especially I want to know if I can change a buttons background color in a thread and if so can someone show me how to write/get me started that thread?
The second question is a follow-up, if you can do this, can you have a like a boolean b which turns to true if someone presses a button and the thread can "notice" that change? For example, if the thread is running and Obama presses button x and b turns "true" in the method OnClick(View v) can I, inside my main thead have an if(b == true){Obama.moon();} and Obama will moon?
Sure you can.
In android you can use the Handler class (example available) to post actions to the event queue. You can do something like this:
final Handler handler = new Handler();
final Runnable updateRunner = new Runnable() {
public void run() {
// we are now in the event handling so to speak,
// so go ahead and update gui, set color of button for instance
}
};
new Thread(new Runnable() {
public void run() {
while (condition) {
SystemClock.sleep(1000);
handler.post(updateRunner);
}
}
}).start();
This will trigger the run in updateRunner each second.
Regarding your follow up, it can be done as well (of course :) ). You can for instance implement an observable pattern to the class that handles the button x. When pressed, notify the observers with something like observers.updateChange(b)
where you previously had a thatClassOverThere.registerObserver(this) in your main thread.

Countdown timer problem on android

Hi I have a countdown timer in my activity oncreate method as follows
start1 = new CountDownTimer(level1time, 1000)
//timer updated every second
{
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//switch activities
}
}
.start();
}
I then call start1.cancel later in my code. This works when this particular activity is started once but when this activity is created again later the activities switch instantly due to the first timer finishing.
My understanding is that a new timer should be created each time the activity is created but that does not seem to be the case. Does anyone know how to fix this problem?
In any case it's better to use Handlers instead of Timers. I generally create a final Runnable object that has what I want run after a certain time, create a new Handler in onCreate(), and post the Runnable to it after a certain delay with postDelayed(Runnable, int). If the user leaves the activity or you ever want it to not execute, you can simply call Handler.removeCallbacks(Runnable) with your defined Runnable to stop the "timer" on it.
That's a high-level approach to your question. Get familiar with the Handler class and this becomes a very easy problem.

Categories

Resources