Meng Tim
Meng Tim

Reputation: 438

How to get the advertising stop event when using bluetooth low energy (BLE)?

I want to write a app to do advertise in android BLE. I want to get the "when advertising stop event", what should I do? I need to do something like: when advertising timeout, do something. But I can I get the timeout or stop event?

Upvotes: 1

Views: 1311

Answers (1)

rothloup
rothloup

Reputation: 1290

Based on your comments, which indicate that you want to advertise for a bit, then stop, your best bet is to use a Handler.

In the Runnable() code, you could either set a flag, as I've done below, or call some other method to handle a more complex operation. If you get a device that connects before the timeout expires, you can call mHandler.removeCallBacks().

import android.os.Handler;

public class thisClase {
    Handler mHandler = new Handler();
    boolean timedOut = false;
    public static final int TIMEOUT = 30*1000; //30 second timeout

    Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            //Put your code to stop advertisting here.
            timedOut = true;
        }
    }

    public void startAdvert() {
        mHandler.postDelayed(mRunnable, TIMEOUT);

        //Put code to start advertising here.
        timedOut=false;
        //Start Advertising.
    }

    //Call this method when a device connects to cancel the timeout.
    public void whenDeviceConnects() {
        //Cancel the runnable.
        mHandler.removeCallbacks(mRunnable);
    }
}

Upvotes: 2

Related Questions