1

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?

raff5184
  • 344
  • 1
  • 2
  • 15

3 Answers3

1

Try to remove call back:

handler.removeCallbacksAndMessages(null);
Humxa Moghal
  • 122
  • 11
  • should I change my method as `public Handler startScanning() { ... ... return handler; }` ? – raff5184 Oct 11 '19 at 12:39
  • 1
    @raff5184 no, just declare handler as Global variable and initialize it in the method. and before removing call backs just put a check if(handler!= null) – Humxa Moghal Oct 11 '19 at 12:42
1
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);
Vikalp Patel
  • 10,669
  • 6
  • 61
  • 96
0

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)

raff5184
  • 344
  • 1
  • 2
  • 15