Java delay function - java

BuzzerControl function is a function that sounds buzzer. I want this function to blink once every three seconds. What should I do? I tried sleep function but it doesn't work.
While(true){
BuzData=1;
BuzzerControl(BuzData);
}

First, we need a Handler that starts the Runnable after 3000ms i.e 3seconds
private Handler handler = new Handler();
handler.postDelayed(runnable, 3000);
And we also need the Runnable for the Handler
private Runnable runnable = new Runnable() {
#Override
public void run() {
/* do what you need to do */
foobar();
/* and here comes the "trick" */
handler.postDelayed(this, 3000);
}
Note:There’s also another advantage of this solution: You don’t have
to create new Timer(Task)s all the time and can reuse the one Handler
and Runnable.

Related

how to call a function every 5 minutes?

I need to call the speak method every 5 minutes, then i want to run in background the async method called callspeak, that calls back the speak method(a public method of a different class). It has to loop every 5 minutes
class callSpeak extends AsyncTask<String, Void, String> {
activityAudio a = new activityAudio();
#Override
protected String doInBackground(String... strings) {
try
{
while (true){
a.speak();
Thread.sleep(300000);
}
}
catch (InterruptedException e)
{e.getMessage();}
return null;
}
}
If you want to run the method only when the app is open, you can simply use TimerTask.
Timer myTimer = new Timer ();
TimerTask myTask = new TimerTask () {
#Override
public void run () {
// your code
callSpeak().execute() // Your method
}
};
myTimer.scheduleAtFixedRate(myTask , 0l, 5 * (60*1000)); // Runs every 5 mins
If you want to run it in background even if app is not running, you can use AlarmManager and repeat the task every 5 mins.
Hope it helps
You can do like this:
Handler mHandler = new Handler();
Runnable mRunnableTask = new Runnable()
{
#Override
public void run() {
doSomething();
// this will repeat this task again at specified time interval
mHandler.postDelayed(this, yourDesiredInterval);
}
};
// Call this to start the task first time
mHandler.postDelayed(mRunnableTask, yourDesiredInterval);
Don't forget to remove the callbacks from handler when you no longer need it.
The latest and the most efficient way to perform this, even if you come out of the activitiy or close the app is to implement the WorkManager from the AndroidX Architecture.
You can find more details here from the official documentation: Schedule tasks with WorkManager

How do I avoid a handler.postDelayed(Runnable run) from being called?

I have this method to scan Bluetooth LE devices. The scanner runs asynchronously for 10s and then it is interrupted.
public void startScanning() {
Handler handler = new Handler();
final long SCAN_PERIOD = 10000;
handler.postDelayed(new Runnable() {
#Override
public void run() {
btScanner.stopScan(leScanCallback);
}
}, SCAN_PERIOD);
btScanner.startScan(leScanCallback);
}
However, depending on a condition that is verified during the scan (for example, I find a device I was looking for, etc.), I call btScanner.stopScan(leScanCallback). So I don't want to call the stopScan after SCAN_PERIOD otherwise I'd call it twice. How do I avoid the second call?
Try to remove call back:
handler.removeCallbacksAndMessages(null);
Handler handler = new Handler();
Runnable runnableRunner = new Runnable() {
#Override
public void run() {
btScanner.stopScan(leScanCallback);
}
}
public void startScanning() {
final long SCAN_PERIOD = 10000;
handler.postDelayed(runnableRunner, SCAN_PERIOD);
btScanner.startScan(leScanCallback);
}
Use removeCallbacks removes any pending posts of Runnable r that are in the message queue.
// cancel runnable whenever your condition is met.
handler.removeCallbacks(runnableRunner);
or use to remove all messages and callbacks
handler.removeCallbacksAndMessages(null);
I have another question on this problem.
I have a method m() in my "sequential" part of the code, not in the asynchronous one, that I need to call only if either the handler.removeCallbacksAndMessages(null); is called, or after the SCAN_PERIOD has expired. How do I check these conditions and basically wait that one of the two happens? Do I need to put m() in a synchronous run?
(Now I also have the global handler that I can use)

Android - How to stop the runnable and handler method

In my application i will be keep on updating some info in some time interval.so i have done like this
handler = new Handler();
and then some Task
handler.postDelayed(runLocation, 1000);
public Runnable runLocation = new Runnable(){
#Override
public void run() {
MainActivity.this.handler.postDelayed(MainActivity.this.runLocation, 100);
};
My problem is i want to stop this runnable at some point of time.how to do this ?
Can you help me?
You can use removeCallbacks. Just call
handler.removeCallbacks(runLocation);
it will remove any pending items in the message's queue.
Use removeCallbacks
#Override
public void run() {
if(isStopHandler){
MainActivity.this.handler.removeCallbacks(this);
return;
}
// do your runnable work
// set isStopHandler = true when needed so next time this method is executed, it will get inside if cond.
};

How do I use a timer to run code again and again until a boolean value e.g. Testing is equal to true?

This is probably a very easy question but, How do I use a timer to run code again and again until a boolean value e.g. Testing is equal to true?
Obviously I would use a while loop but I don't want it to stop the rest of the work taking place on the main ui thread
If your process is running simultaneously, use a Handler and use its postDelayed(Runnable, long) to post a callback implementing the Runnable interface.
A rather naive example:
final handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
if (<EXPRESSION>) {
// Evaluated true, do your stuff and exit the polling loop.
} else {
handler.postDelayed(this, <TIMEOUT>);
}
}
handler.postDelayed(r, <TIMEOUT>);
You can use AlarmManager class to manage your thread. its simple to use.
for more info you can visit Android SDK Doc
timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Do your task
if(flagIsOn)
{
timer.cancel();
timer.purge();
}
}
}, 0, 1000);

What is better for instructions at roughly the same time: multiple Handlers with single Runnable each, or single Handler with multiple Runnables?

So I want several things to go off exactly at once while trying to maintain a light resource load. For example, play sound and updating GUI at the same time. Is it better to have multiple handlers with single runnables or a single handler with multiple runnables running in parallel?
I'm aware that the below implementation won't actually run at the same time and be offset due to instructions in runnable1 potentially being longer than runnable2 thus (runnable1 execution time + 3000) vs (runnable2 time + 6000), etc. But let's just say 3000 and 6000 are substitutes for calculated time to make it run every three seconds (take the difference in milliseconds of next interval [e.g. 00:00:03.000, 00:00:06.000] and the current time).
private Handler handler1 = new Handler();
private Handler handler2 = new Handler();
protected void onStart() {
super.onStart();
Runnable runnableH1 = new Runnable() {
#Override
public void run() {
/* playSound A,B,C, etc every three seconds */
handler1.postDelayed(this, 3000);
}
}
};
Runnable runnableH2 = new Runnable() {
#Override
public void run() {
/* change GUI A,B,C, etc every six seconds */
handler2.postDelayed(this, 6000);
}
}
};
handler1.postDelayed(runnableH1, 0);
handler2.postDelayed(runnableH2, 0);
}
vs
private Handler handler1 = new Handler();
protected void onStart() {
super.onStart();
Runnable runnable1 = new Runnable() {
#Override
public void run() {
/* playSound A,B,C, etc every three seconds */
handler1.postDelayed(this, 3000);
}
}
};
Runnable runnable2 = new Runnable() {
#Override
public void run() {
/* change GUI A,B,C, etc every six seconds */
handler1.postDelayed(this, 6000);
}
}
};
handler1.postDelayed(runnable1, 0);
handler1.postDelayed(runnable2, 0);
}
I'm aware that there are similar questions:
Android: one handler for all runnables?
But the answers say you can only use one handler when from my reading of the Android documentation it sounds like you can implement multiple handlers w/o issue (else the IDE would complain, which it doesn't) to have multiple threads.
It doesn't really matter if in the end all you are doing with the handlers is changing views or any other task that will be added to the main UI, you can have a single handler attached to the main Looper and or several of them, in the end all of your handlers(or your single handler) will be piping messages into a single queue, "the main thread UI queue", so, there's no real advantage from a "parallelism/multithreading" stand point.
Personally I would avoid having several handlers because it would be error prone and chances to get leaks are higher...
On the other hand, if you are not pushing your messages to the main thread and in stead you are just doing some work in parallel, then several threads is the way to go, not necessarily several handlers since you actually don't really need them unless you need to publish something into the main thread.
Hope it helps!
Regards

Categories

Resources