使用蓝牙低功耗(BLE)时如何获得广告停止事件?

时间:2016-02-18 16:01:55

标签: android bluetooth-lowenergy

我想写一个应用程序在android BLE做广告。我想得到“广告停止时”,我该怎么办?我需要做一些事情:当广告超时时,做一些事情。但我可以得到超时或停止事件吗?

1 个答案:

答案 0 :(得分:2)

根据您的评论,表明您想宣传一点,然后停止,您最好的选择是使用Handler

Runnable()代码中,您可以设置一个标志,如下所示,或者调用其他方法来处理更复杂的操作。如果您在超时到期之前获得了连接的设备,则可以致电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);
    }
}