My task is that if within 90 seconds no MotionEvent occurs, there are no clicks on the buttons, then a certain method is called. How can I call a method if within 90 seconds there is no action?
There is a number of alternative ways to do this
Now currently it is running every 2 min change accordingly
ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
// This schedule a runnable task every 2 minutes
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
doSomethingUseful();
}
}, 0, 2, TimeUnit.MINUTES); // change accordingly
OR
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
#Override
public void run() {
yourfunction();
handler.postDelayed(this, 1000);
}
};
//Start
handler.postDelayed(runnable, 1000);
Related
I want to make a text view changing for every 5sec for 5 times(Note: I want a sequential call one after another unlike threads ) in Android.
call x
wait for 5 seconds
call x
wait for 5 seconds
call x
wait for 5 seconds
call x
wait for 5 seconds
call x
for(i=0;i<n;i++){
x();
thread.sleep(5*1000);
}
If want to do it in Android, you can use Handlers
Try this
private int run = 0;
private Handler handler=new Handler();
private Runnable runnable=new Runnable() {
#Override
public void run() {
xMethod();
// Put your code here, what you want to do 5 times
}
};
And the method is
private void xMethod(){
handler.postDelayed(runnable, 5000);
if (run >= 5) {
handler.removeCallbacks(runnable);
Log.e("xMethod","handler canceled");
}
run++;
Log.e("xMethod","X Method runs");
}
You just need to put the code in the run method of Runnable and called it from anywhere in the class xMethod();
Hey use Handler and Runnable so that you can call one after another after an fix interval of time.
private Handler mHandler = new Handler(); //use import android.os.Handler;
private Runnable mRunnable;
private int counter = 0; //To count how many times the method is called
private long timeGap = 1000 * 5; // this is in millisecond means 5 second here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...existing code
//call your x method direct in onCreate or in any event listener like below
mHandler.post(mRunnable);
//...existing code
}
mRunnable = new Runnable() {
#Override
public void run() {
if(counter < 5) {// mean max repeated call
//call your X method (say yourXMethod()) here
yourXMethod();
counter++;
//Now call handler again to call method after timeGap interval of time.
mHandler.postDelayed(mRunnable, timeGap);
//if you don't want any time gap in between two method call then call like "mHandler.post(mRunnable);"
} else {
//delink the runnable with the handler.
mHandler.removeCallbacks(mRunnable);
}
}
};
Let me know if it fulfilled your requirement.
I want run timer for about 30000 ms and up to 8 or more times each so here is my loop but it runs all timers at once after 30000ms
public void repeatTimerTask() {
repeat = 8; // need to run 30 sec timer for 8 times but one after one
startTimer(30000); // firsat timer for 30 sec
Handler handler = new Handler();
for (int a = 1; a<=repeat; a++) {
final int finalA = a;
handler.postDelayed(new Runnable() {
#Override
public void run() {
startTimer(30000);
}
}, 30000); // delay until to finish first timer for 30 sec
}
}
To run a timer for n seconds you can use CountDownTimer
Declare two varibales globbaly. One for number of times you want to repeat. and one to keep the count of repetaion.
private int NUM_REPEAT = 4;
private int REPEAT_COUNT = 0;
Then call this method wherever you want. One thing to note if you want to run this loop 5 times you have to give number of repeation 4. Cause to satrt this function you have to call it so that will not come in count.
private void startTimer() {
new CountDownTimer(3000, 1000) {
int secondsLeft = 0;
public void onTick(long ms) {
if (Math.round((float) ms / 1000.0f) != secondsLeft) {
secondsLeft = Math.round((float) ms / 1000.0f);
// resend_timer is a textview
resend_timer.setText("remaining time is "+secondsLeft);
;
}
}
public void onFinish() {
Log.d(TAG, "timer finished "+REPEAT_COUNT);
if (REPEAT_COUNT <= NUM_REPEAT) {
startTimer();
REPEAT_COUNT++;
}
}
}.start();
}
Please try the below code, and call 'startTimer' method where you first want to start your timer :
private int startTimerCount = 1, repeat = 8;
private void startTimer(){
// if startTimerCount is less than 8 than the handle will be created
if(startTimerCount <= repeat){
// this will create a handler which invokes startTimer method after 30 seconds
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startTimer();
}
}, 30000);
// do what you want
Toast.makeText(this, "startTimer " + startTimerCount, Toast.LENGTH_SHORT).show();
}
startTimerCount++;
}
This question already has answers here:
How to run a thread repeatedly after some interval
(3 answers)
Closed 4 years ago.
I am developing an Android App in which I need to run a piece of code every minute, when I say every minute I mean it should be synced with the device's time so every time the device time changes by one minute my code is executed.
So far I tried this but it is not working:
runnable=new Runnable(){
#Override
public void run(){
long now=SystemClock.uptimeMillis();
long next=now+(60000 - now % 60000);
handler.postAtTime(this, next);
}
};
runnable.run();
There are many other ways to do this:
1) Timer.scheduleAtFixedRate()
2) Thread.sleep(interval)
3) Alarm Manager
In your way it will look like this:
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
try{
//do your code here
}
catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable to call it at regular interval
handler.postDelayed(this, "*interval");
}
}
};
handler.postDelayed(runnable, "*interval");
you can see this answer for details
You can use this code:
Thread thread = new Thread(new Runnable()
{
int lastMinute;
int currentMinute;
#Override
public void run()
{
lastMinute = currentMinute;
while (true)
{
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
currentMinute = calendar.get(Calendar.MINUTE);
if (currentMinute != lastMinute){
lastMinute = currentMinute;
Log.v("LOG", "your code here");
}
}
}
});
thread.run();
one can use handle and can give input as milliseconds and we can call the code for every minute and should not use any infinite loops while using two different layouts
final Handler handler = new Handler();
Runnable run = new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 60000);
}
};
handler.post(run);
You can use handler if you want to initiate something every X seconds. Handler is good because you don't need extra thread to keep tracking when firing the event. Here is a Code:
private final static int INTERVAL = 1000 * 60 * 1; //1 minutes
Handler mHandler = new Handler();
Runnable mHandlerTask = new Runnable()
{
#Override
public void run() {
doSomething();
mHandler.postDelayed(mHandlerTask, INTERVAL);
}
};
void startRepeatingTask()
{
mHandlerTask.run();
}
void stopRepeatingTask()
{
mHandler.removeCallbacks(mHandlerTask);
}
The modern method
new Handler().postDelayed(() -> {
}, 30000);
I am writing simple game, where some action must accelerating during the process. The question is how to change timer's period?
timer = new Timer();
timerTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//
// I need to change timer's period here
//
}
});
}
};
timer.schedule(timerTask, 0, period);
Will be glad to hear any advices.
I assume that you are performing some logic within the run() method of the TimerTask.
I think a simpler way to go about this would be to use a Handler. This is possibly more idiomatic for Android:
private final Handler mHandler = new Handler();
private final Runnable mTask = new Runnable() {
#Override
public void run() {
// Do your logic.
// Now post again.
mHandler.postDelayed(mTask, /* choose a new delay period */);
}
};
public void init() {
delay = 1000L; // 1 second.
mHandler.postDelayed(mTask, delay);
}
I'm currently using a Timer and TimerTask to perform some work every 30 seconds.
My problem is that after each time I do this work I want to increment the interval time of the Timer.
So for example it starts off with 30 seconds between the timer firing but I want to add 10 seconds to the interval then so that the next time the Timer takes 40 seconds before it fires.
Here is my previous code:
public void StartScanning() {
scanTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
wifiManager.startScan();
scanCount++;
if(SCAN_INTERVAL_TIME <= SCAN_MAX_INTERVAL){
SCAN_INTERVAL_TIME = SCAN_INTERVAL_TIME + SCAN_INCREASE_INTERVAL;
t.schedule(scanTask, 0, SCAN_INTERVAL_TIME);
}
}
});
}};
Log.d("SCAN_INTERVAL_TIME ** ", "SCAN_INTERVAL_TIME ** = " + SCAN_INTERVAL_TIME);
t.schedule(scanTask, 0, SCAN_INTERVAL_TIME);
}
REFACTORED CODE
#Override
public void StartScanning() {
t.schedule(new ScanTask(),SCAN_INTERVAL_TIME);
}
class ScanTask extends TimerTask{
#Override
public void run() {
wifiManager.startScan();
scanCount++;
if(SCAN_INTERVAL_TIME < SCAN_MAX_INTERVAL)
SCAN_INTERVAL_TIME = SCAN_INTERVAL_TIME + SCAN_INCREASE_INTERVAL;
t.schedule(new ScanTask(), SCAN_INTERVAL_TIME);
}
}
It works now but is creating a new ScanTask() every time wasteful?
Here is how I would do it:
1) Schedule the task for a single execution rather than a repeated one
2) At the end of the execution (possibly in a finally block), schedule a new single execution of the task, with a longer delay. Note that you must create a new instance of the task, otherwise the timer will complain (IllegalStateException). That means that you can't use an anonymous inner class anymore.