I have this button which i want to set a timer to it so that the user do not have to click it everytime, such that it auto click this button every 20seconds. How do i set it?
Basically i am using a tabhost activity, so there're total of 3 tabs. In the first tab, there is this button which i need to click the button therefore i then able to retrieve informations from webservice and this webservice will update every time. When i click on other tabs and back to the first tab, i want it to be auto refresh.. Instead of clicking the button to refresh.
holder.btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
A more efficient way IMO is using ScheduledExecutorService:
private void doTheActualJobWhenButtonClicked() {
// put whatever you need to do when button clicked here
... ...
}
... ...
holder.btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// job triggered by user click button:
doTheActualJobWhenButtonClicked();
}
});
... ...
ScheduledExecutorService scheduleTaskExecutor= Executors.newScheduledThreadPool(1);
// This schedule a task to run every 20 seconds:
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
// job triggered automatically every 20 seconds:
doTheActualJobWhenButtonClicked();
}
}, 0, 20, TimeUnit.SECONDS);
UPDATE:
If your button click perform some UI update for example refresh text in a TextView, then simply wrap
your method call within runOnUiThread():
private void doTheActualJobWhenButtonClicked() {
myTextView.setText("refreshed");
}
ScheduledExecutorService scheduleTaskExecutor= Executors.newScheduledThreadPool(1);
// This schedule a task to run every 20 seconds:
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
// involved your call in UI thread:
runOnUiThread(new Runnable() {
public void run() {
doTheActualJobWhenButtonClicked();
}
});
}
}, 0, 20, TimeUnit.SECONDS);
Also you need shutdown ScheduledExecutorService properly before open next Activity or close your current Activity:
// Shut down scheduled task before starting next activity
if (scheduleTaskExecutor != null)
scheduleTaskExecutor.shutdownNow();
Intent intent = new Intent(getBaseContext(), NextActivity.class);
startActivity(intent);
... ...
public void onDestroy() {
super.onDestroy();
// Shut down scheduled task when closing current activity
if (scheduleTaskExecutor != null)
scheduleTaskExecutor.shutdownNow();
}
Hope this help.
Since you have a button, I assume that you have an ActionPerformed-type method at someplace.
Given that, you can do this:
public class AutoClick extends Thread {
// Time to wait in milliseconds
private long wait;
//Latency excepted
private long lat;
AutoClick(long time, long latency) {
wait = time;
lat = latency;
}
public void run() {
long start = System.getCurrentTimeMillis();
long current;
while(true)
current = System.getCurrentTimeMillis();
long step = (current-start) % 20000;
if(step <= latency || step >= wait-latency)
//call the action-performed method
}
}
Then create an instance of the thread and run it:
public AutoClick clicker = new AutoClick(20000);
clicker.run();
Related
I want to set network status in TextView, which I want to repetitively call method and set in background, so I used AsyncTask class with infinite loop
class setNetworkText extends AsyncTask
{
#Override
protected Object doInBackground(Object[] params) {
for(;;)
{
if(isNetworkConnected()) //check internet connection and if found it return true
setOnline(); // it set my TextView text to Online
else
setOffline(); // it set my TextView text to Offline
Thread.sleep(2000);
}
return null;
}
}
but it is not working, it stops my application.
Android will (in most versions) only execute one AsyncTask at a time - so if you keep blocking in doInBackground of one AsyncTask, no other AsyncTasks will run, thus blocking your application.
Take a look at using Handler.postDelayed or using a TimerTask. They are more suited for repeating actions.
You can not use AsyncTask to do that. You should use Handler to schedule a task periodically.
// Create the Handler
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableTask = new Runnable() {
#Override
public void run() {
if(isNetworkConnected())
setOnline();
else
setOffline();
}
};
// Call on main thread (for example, inside onResume())
#Override
protected void onResume() {
super.onResume();
handler.postDelayed(runnableTask, 2000);
}
// Remember to unregister it onPause()
#Override
protected void onPause() {
super.onPause();
handler.removeCallbacks(runnableTask);
}
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
//check something on time interval here 1 second
}
public void onFinish() {
//when your task done here 3 second is time to end
}
}.start();
explanation
CountDownTimer(long millisInFuture, long countDownInterval)
millisInfuture will be how long you want to run the task and countDownInterval is the interval in your case it is 2 seconds
I want to make an application about mini game.
Detail : In 2 seconds you must to answer a question if you don't answer or the answer is wrong -> Game Over . But if your answer is true the Timer will reset become 0 and countdown again with diffirent question.
I have already seen many code about timer in website but I don't understand clearly about it :(
So I want to ask : How can i set up a timer run only 2 seconds and how can i reset it and continue with a new question ?
Please help me.
you can use CountDownTimer in android like this:
public class Myclass {
myTimer timer =new myTimer(2000,1000);
public void creatQuestion(){
timer.start();
//method you init question and show it to user
}
public void getUserAnswer(/*evry thing you expected*/)
{
//if answer is true call timer.start()
//else call timer.onFinish(); to run onfinish in timer
}
public class myTimer extends CountDownTimer {
public myTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
// you can update ui here
}
#Override
public void onFinish() {
this.cancel();
//fire game over event
}
}
}
i hope it make you satisfy
I've done something similar using Thread/Runnable.
Thread t = new Thread(new Runnable() {
public void run() {
final long startTime = getTime();
final long maxEndTime = startTime + 2000L;
try {
while (shouldContinueWaiting()) {
if (getTime() > maxEndTime) {
throw new TimeoutException();
}
sleep();
}
} catch (InterruptedException e) {
handleInterrupt();
} catch (TimeoutException e) {
handleTimeout();
}
}
boolean shouldContinueWaiting() {
// Has the user already answered?
}
void handleInterrupt() {
// The user has answered. Dispose of this thread.
}
void handleTimeout() {
// User didn't answer in time
}
void sleep() throws InterruptedException {
Thread.sleep(SLEEP_DURATION_IN_MILLIS);
}
void getTime() {
return System.currentTimeMillis();
}
then you can start/restart the thread by:
t = new Thread(same as above...);
t.start();
and stop by:
t.interrupt();
We want to use the Timer class.
private Timer timer;
When you're ready for the timer to start counting -- let's say it's after you press a certain button -- do this to start it:
timer = new Timer();
timer.scheduleAtFixedRate(incrementTime(), 0, 100);
The first line is us creating a new Timer. Pretty standard. The second line, however, is the one I wanted you to see.
incrementTime() is a method that is called at the end of every "tick" of the clock. This method can be called whatever you want, but it has to return an instance of TimerTask. You could even make an anonymous interface if you want, but I prefer moving it off into its own section of code.
The 0 is our starting location. We start counting from here. Simple.
The 100 is how large a "tick" of the clock is (in milliseconds). Here, it's every 100 milliseconds, or every 1/10 of a second. I used this value at the time of writing this code because I was making a stopwatch application and I wanted my clock to change every 0.1 seconds.
As for your project, I'd suggest making the timer's task be your question switch method. Make it happen every 2000 milliseconds, or 2 seconds.
You can use a Handler.
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
//this will happen after 2000 ms
}
}, 2000);
Maybe this can help you:
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
// FIRE GAME OVER
handler.postDelayed(this, 2000); // set time here to refresh textView
}
});
You can fire your game over after 2000 milliseconds.
If you get the question correct -> remove callback from handler and reset it when the next question starts.
I am creating an app which is like a memory game. A button has an image resource from a drawable and I want to the background resource of a button to go back to its default background, say after 5 seconds.
Here is my code.
Collections.shuffle(ShapesArray);
this.myImg1=ShapesArray.get(0);
img1.setBackgroundResource(myImg1);
task = new TimerTask(){
#Override
public void run() {
// TODO Auto-generated method stub
img1.setBackgroundResource(android.R.drawable.btn_default);
}
};
Timer appear = new Timer();
appear.schedule(task, 5000);
img1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
img1.setBackgroundResource(myImg1);
String txt = PName.getText().toString();
if(txt.equals("Heart")){
if(myImg1 == R.drawable.heart){
correct++;
img1.setBackgroundResource(android.R.drawable.btn_default);
}
}
However, after the 5 Seconds, the Activity force closes and goes back to previous activity. I'm kinda new to Android. Please help. :(
You can use either handler with post delay or can use count down timer ,here i am giving an example of count down and that is-
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
//This is when you click on each tick it came here after 1000 millisecond
}
public void onFinish() {
// After the time is experied so here can change image
Printer.setBackgroundResource(R.drawable.prntr);
}
}.start();
Thanks
I have a TextView. I want to update its text (append a "1") after 1 second of a button click.
public class HaikuDisplay extends Activity {
Method m;
Timer t;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = new Timer();
m = HaikuDisplay.class.getMethod("change");
}
//Event handler of the button
public void onRefresh(View view)
{
//To have the reference of this inside the TimerTask
final HaikuDisplay hd = this;
TimerTask task1 = new TimerTask(){
public void run(){
/*
* I tried to update the text here but since this is not the UI thread, it does not allow to do so.
*/
//Calls change() method
m.invoke(hd, (Object[])null);
}
};
t.schedule(task1, 1000);
}
public void change()
{
//Appends a "1" to the TextView
TextView t = (TextView)findViewById(R.id.textView1);
t.setText(t.getText() + "1");
}
//Event handler of another button which updates the text directly by appending "2".
//This works fine unless I click the first button.
public void onRefresh1(View view)
{
TextView t = (TextView)findViewById(R.id.textView1);
t.setText(t.getText() + "2");
}
}
Consider all Exceptions be handled.
On first click, m.invoke gives InvocationTargetException. But it calls the method change() on successive invokes without any Exceptions(verified by logging). But it does not update the text. Where am I wrong?
Also, I see in the debugger that it creates a new Thread every time I click the button. That is fine. But why isn't it removing the previous Threads though their execution has been completed?
Do something like this
public void onRefresh1(View v) {
// You can have this in a field not to find it every time
final EditText t = (EditText) findViewById(R.id.textView1);
t.postDelayed(new Runnable() {
#Override
public void run() {
t.append("1");
}
}, 1000);
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Update UI
}
}, 1000);
implement this on button click
UPDATE:
There are some other answers. dtmilano suggested another solution which is almost same to mine except he is calling the postDelayed method of View class and In my answer I used postDelayed method of handler class.
from the api reference of android the postDelayed method of Handler says
The runnable will be run on the thread to which this handler is
attached.
and the postDelayed method of View says
The runnable will be run on the user interface thread.
This is the only difference between these two solution. in my answer instead of creating new Handler every time you can use any other handler instance. Then the runnable will be run on that thread where that specific handler is declared. And if the postDelayed of EditText is used the the runnable method will be run on the user Interface Thread.
Now the performance issue, both has the same performance (If anybody can prove me wrong with reference I will be happy)
That's looking awful convoluted - have you considered using CountDownTimer instead?
new CountDownTimer(1000, 1000) {
public void onTick(long millisUntilFinished) {
// no-op
}
public void onFinish() {
change();
}
}.start();
This should call change (and hence change the text) on the UI thread, avoiding reflection and threading errors.
Hi Use the following code for that. Hope this will help you .
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
// your code here
}
},
1000
);
Have a look of this question also.
display data after every 10 seconds in Android
You can try with this also.
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
public void run() {
doStuff();
/*
* Now register it for running next time
*/
handler.postDelayed(this, 1000);
}
};
**EDIT 3**
Try with this once you are need to enable once (i mean if you put your code in yourmethod()== this will get automatically call 1 seconds once.
private Timer timer;
TimerTask refresher;
// Initialization code in onCreate or similar:
timer = new Timer();
refresher = new TimerTask() {
public void run() {
yourmethod();
};
};
// first event immediately, following after 1 seconds each
timer.scheduleAtFixedRate(refresher, 0,100);
I have an app that shows a disclaimer at the beginning of the program. I want a button to remain invisible for a set amount of time, and then become visible.
I set up a thread that sleeps for 5 seconds, and then tries to make the button visible. However ,I get this error when I execute my code:
08-02 21:34:07.868: ERROR/AndroidRuntime(1401): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
How can I count 5 seconds, and then make the button visible?
THanks.
Thread splashTread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
while(_active && (!_ok2)) {
sleep(100);
if(_active) {
waited += 100;
if(waited >= _splashTime)
{
turnButtonOn();
}
}
}
} catch(InterruptedException e) {
// do nothing
} finally {
finish();
startActivity(new Intent("com.lba.mixer.Choose"));
}
};
splashTread.start();
public static void turnButtonOn() {
okButton.setVisibility(View.VISIBLE);
}
The problem is that you're not in the UI thread when you call okButton.setVisibility(View.VISIBLE);, since you create and run your own thread. What you have to do is get your button's handler and set the visibility through the UI thread that you get via the handler.
So instead of
okButton.setVisibility(View.VISIBLE)
you should do
okButton.getHandler().post(new Runnable() {
public void run() {
okButton.setVisibility(View.VISIBLE);
}
});
I found this to be a much simpler solution. Visibility on 7 second delay
continuebutton.setVisibility(View.INVISIBLE);
continuebutton.postDelayed(new Runnable() {
public void run() {
continuebutton.setVisibility(View.VISIBLE);
}
}, 7000);
I found this a Better solution to the problem
(button id = but_resend)
define handler
private Handler handler;
call function in extend class
showButtons();
define after class
private void showButtons() {
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
((Button) findViewById(R.id.but_resend)).setVisibility(View.VISIBLE);
}
}, 20000); // produce 20 sec delay in button visibility
}
and keep in mind to hide the visibility in the.xml file by
android:visibility="invisible"