Android - How to stop the runnable and handler method - java

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.
};

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

Java delay function

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.

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)

I want timer/handler or something else to run some specific function twice?

When I start the app "specific function" needs to be executed.
After 10 seconds "specific function" needs to be triggered again.
After this second operation "specific function" should not triggered again.
There are two way to handle your problem.
If there is any condition you want to check and accordingly do the work after every 10 seconds You should Use a Handler.
If there is no condition on anything and you just want to run the code after every 10 Seconds. Then TimerTask is also one way. I have actually worked with TimerTask class. So i say it is quite easy.
Creating your class and implementing the methods.
class myTaskTimer extends TimerTask{
#Override
public void run() {
Log.e("TAG", "run: "+"timer x");
}
}
and now in your code Create a new Timer Object and initialize it.
Timer t = new Timer();
Now you can schedule your task in it after a specified interval like below:
t.scheduleAtFixedRate(new myTaskTimer(),10000,10000);
The function is explained below:
void scheduleAtFixedRate (TimerTask task,
long delay,
long period)
Schedules the specified task for repeated fixed-rate execution,
beginning after the specified delay. Subsequent executions take place
at approximately regular intervals, separated by the specified period.
and now for handler , below is the code and it can check for any condition. Code taken from here for your help.
private int mInterval = 10000; // 10 seconds as you need
private Handler mHandler;
#Override
protected void onCreate(Bundle bundle) {
// your code here
mHandler = new Handler();
startRepeatingTask();
}
#Override
public void onDestroy() {
super.onDestroy();
stopRepeatingTask();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
try {
updateStatus(); //this function can change value of mInterval.
} finally {
// 100% guarantee that this always happens, even if
// your update method throws an exception
mHandler.postDelayed(mStatusChecker, mInterval);
}
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
I hope it helps.
Use android.os.Handler as per #pskink comment.
private void callSomeMethodTwice(){
context.myMethod(); //calling 1st time
new Handler().postDelayed(new Runnable(){
#Override
public void run(){
context.myMethod(); //calling 2nd time after 10 sec
}
},10000};
}

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);

Categories

Resources