1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.clj.fastble.scan;
 
import android.bluetooth.BluetoothAdapter;
import android.os.Handler;
import android.os.Looper;
 
import com.clj.fastble.bluetooth.BleBluetooth;
 
public abstract class PeriodScanCallback implements BluetoothAdapter.LeScanCallback {
 
    private Handler handler = new Handler(Looper.getMainLooper());
    private long timeoutMillis = 10000;
    BleBluetooth bleBluetooth;
 
    PeriodScanCallback(long timeoutMillis) {
        this.timeoutMillis = timeoutMillis;
    }
 
    public abstract void onScanTimeout();
 
    public abstract void onScanCancel();
 
    public void notifyScanStarted() {
        if (timeoutMillis > 0) {
            removeHandlerMsg();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    bleBluetooth.stopScan(PeriodScanCallback.this);
                    onScanTimeout();
                }
            }, timeoutMillis);
        }
    }
 
    public void notifyScanCancel() {
        bleBluetooth.stopScan(PeriodScanCallback.this);
        onScanCancel();
    }
 
    public void removeHandlerMsg() {
        handler.removeCallbacksAndMessages(null);
    }
 
    public long getTimeoutMillis() {
        return timeoutMillis;
    }
 
    public PeriodScanCallback setTimeoutMillis(long timeoutMillis) {
        this.timeoutMillis = timeoutMillis;
        return this;
    }
 
    public BleBluetooth getBleBluetooth() {
        return bleBluetooth;
    }
 
    public PeriodScanCallback setBleBluetooth(BleBluetooth bluetooth) {
        this.bleBluetooth = bluetooth;
        return this;
    }
}