I have been using 5 Handler tasks in my application with different post delays but all of them are working at a different speed irrespective of the delay time that I have specified, is there a better way to get exact time delay in between of multiple tasks,
Sample Code:
H2 = new Handler();
R2 = new Runnable()
{ #Override
public void run()
{ H2.postDelayed(R2, 100);
//Do something
}
};
H2.postDelayed(R2, 0);
Task would run in variable time intervals sometimes way more variable.
Related
So, I borrowed a timer approach from this excellent post:
Android timer? How-to?
which was very well-written and well-upchecked. However, I find that it fires approximately every 106-114msec, not the desired 100msec. Does this make sense, or does it seem slow? If I wanted to make this closer to an exact 100msec (I am using it in some places to measure durations), what change should I make?
My code is below
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
TickTimer_Elapsed();
timerHandler.postDelayed(this, 100);
}
};
void TickTimer_Start() { timerHandler.postDelayed(timerRunnable, ); }
void TickTimer_Stop() { timerHandler.removeCallbacks(timerRunnable); }
void TickTimer_Elapsed()
{
m_FSM.Tick_10Hz(); // actually a bit slower than 10Hz
}
Timer is overloaded term in English, meaning either a device that measures time (e.g. a stopwatch), or a device that triggers after a time (e.g. egg timer).
In Android, the timer is for the latter only, and it does not promise absolute accuracy.
"I am using it in some places to measure durations"
In real life, to tell how much time has passed, you would not to watch a clock and count the seconds ticking by! You'd get nothing else done in that time. An efficient way would be to look at the clock just twice and subtract the two times. The same is true with computers:
e.g:
long startTimeMs = System.currentTimeMillis();
Later:
long durationMs = System.currentTimeMillis() - startTimeMs;
On button click I want to begin a timer of 5 minutes and then execute a method that will check for certain conditions and set off alerts if conditions are right. I've seen examples with timers and postDelay, but don't really understand why one would use one vs another. What is the best way to accomplish what I am trying to do? I don't want to lock up the UI during the 5 minutes. The user should be free to use the app as normal during the countdown.
EDIT: I am trying the postDelayed suggestion but visual studio is not liking something about my code. It looks exactly like examples I've found. My be a mono for android thing.
Handler h = new Handler();
Runnable r = new Runnable(){
public void run()
{
Dialog d = inst2.showBuilder(this, "test", "test");
d.Show();
}
};
h.postDelayed(r, 5000);
Specifically the code block inside of run throws all kinds of "} expected" and "a namespace cannot directly contain members such as fields or methods" exceptions.
Try using Timer Object :
Timer mTimer = new Timer();
mTimer.schedule(new TimerTask()
{
#Override
public void run()
{
// Your code goes here
}
}, 1000); // 1sec
final Handler handler = new Handler();
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
#Override
public void run()
{
handler.post(new Runnable()
{
public void run()
{
// YOUR Code
}
});
}
}, 1000); // 1sec
You can start a simple Thread that will sleep in background for 5 minutes and then call a function. While the thread sleeps in background the UI will not freeze. When the thread finish executing what you want you can set off alerts by sending some intents as notifications and receive them in some Broadcast Receivers.
Hope this helps
Use Handler.postDelayed(Runnable block); method to execute delay, as android also not recommend to use timer.
Handler h = new Handler();
Action myAction = () =>
{
// your code that you want to delay here
};
h.PostDelayed(myAction, 1000);
can someone give me the code example that shows how to use two different threads on a single service? i didnt find the way to do it in google, then i need a code example...
one waiting 5 seconds and the other waiting 60 seconds, with different code
You can use the ScheduledExecutorService to create and run scheduled events, then set them up like this:
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
final Runnable r1 = new Runnable() {
#Override
public void run() {
Log.i("TestStuff", "r1 ran at " + new Date());
}
};
final Runnable r2 = new Runnable() {
#Override
public void run() {
Log.i("TestStuff", "r2 ran " + new Date());
}
};
scheduler.schedule(r1, 5, TimeUnit.SECONDS);
scheduler.schedule(r2, 60, TimeUnit.SECONDS);
Note that the threads can't do anything on the UI, but you did mention a "single service", so i'm assuming you're doing all non-UI things anyway.
Thread t5 = new Thread(Runnable_that_waits_5_seconds);
Thread t60 = new Thread(Runnable_that_waits_60_seconds);
t5.start();
t60;start();
Now you just need to define your runnables.
Also, you should give your runnables a way to detect that they've been interrupted and terminate if they do, and interrupt each thread in your service's clean-up code.
I'm using a runnable in my Android app to update a countdown timer, as shown in the code below. It appears to work but I noticed my timer takes a few seconds longer than expected. For example, if it's supposed to count down 3 minutes, it takes 3 minutes and 5 seconds. I tried using a timer in a service to manage the countdown display in the main activity. The timer/service worked as expected.
Why doesn't runnable/postDelayed() run for the correct amount of time? Is postDelayed() timing reliable? The runnable decrements a variable then uses it to update an EditText with setText(). Does setText() take too long (a small fraction of a second), so the runnable really runs every 1.x seconds?
Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
// decrement the time remaining and update the display
handler.postDelayed(this, 1000);
}
};
...
// start the runnable
handler.postDelayed(r, 1000);
Your code is kinda sorta designed to be inaccurate because you are not accounting for the time taken by the guts of the runnable. You might get improved results by doing something like
public void run(){
startTime = System.currentTimeMillis();
// compare expectedTime to startTime and compensate
// <guts of runnable goes here>
// now wrap it up...
delay = 1000 - (System.currentTimeMillis() - startTime);
if (delay < 0)
delay = 0;
expectedTime = System.currentTimeMillies() + delay;
handler.postDelayed(this, delay);
}
What about using CountDownTimer? I used this for same tasks several times and haven’t met this kind of problem.
I have an android app that repeatedly collects fingerprints from the wifi-networks that are around (for scientific reasons, not to invade anybodies privacy).
Anyways, imagine I have a function that does this work and it's called scanWifi(). I initally wanted to start it like this:
ExecutorService mExecutor = Executors.newSingleThreadScheduledExecutor();
mExecutor.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
scanWifi();
}
}, 0, interval, TimeUnit.MILLISECONDS);
Sadly, this only works reliably when the phone is plugged in. If it's plugged out and lays there for a while, it doesn't run my scanWifi() function every minute. Sometimes there are gaps of several minutes between single calls to scanWifi().
I also tried doing the same thing using a Timer/TimerTask with similarly poor results.
The only thing that seems to work more or less reliable until now is to post it to a handler and call it repeatedly, like this:
Handler h = new Handler();
Runnable r = new Runnable() {
#Override
public void run() {
if (!mIsStopped) {
scanWifi();
h.postDelayed(this, mInterval);
}
}
};
h.post(r);
Why is that the case? Is the CPU sleeping and thus misses the scheduled execution? I hold a partial wakelock in my app.
I think what you're looking for is an AlarmManager. See, for example, this question: Android: How to use AlarmManager