cnkaptan
cnkaptan

Reputation: 15

how to cancel timer and handler with stopping their proccess?

I wanna stop the current timer proccess with inside handler but when I run mTimer.cancel() , I am terminating timer instance but mHandler and its process continues their action. I tried to use mHandler.removeCallbacks() but it didnt work well.

    mTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            Log.e(TAG, "scan started");
            mScanning = true;
            mBluetoothAdapter.startLeScan(mLeScanCallback);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    triggerListener();
                    Log.e(TAG, "scan stopped");
                    mScanning = false;
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                }
            }, scanPeriod);
        }
    }, new Date(), betweenScanPeriod + scanPeriod);

Upvotes: 0

Views: 54

Answers (2)

Edson Menegatti
Edson Menegatti

Reputation: 4036

The method removeCallback() won't stop a runnable that is currently running as stated in the documentation:

Remove any pending posts of Runnable r that are in the message queue

When the runnable is executing, it is no longer pending/in the message queue so it is not possible to cancel it from outside. As @Opiatefuchs said, you'll need to get a reference to the handler to which the runnable was posted and send a message to it:

Handler mHandler = new Handler();
Message message = mHandler.obtainMessage();
mHandler.sendMessage(message);

In the handler you'll override the handleMessage() and stop the runnable by setting some variable that will stop it as soon as possible. This means both the runnable and the handler must share at least one variable. You can find more info in this post.

Upvotes: 1

Bojan Kseneman
Bojan Kseneman

Reputation: 15668

You need to keep a reference to the Runnable you are posting and remove it

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            triggerListener();
            Log.e(TAG, "scan stopped");
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
    };


// And cancel it
mHandler.removeCallbacks(runnable);

Upvotes: 0

Related Questions