张海江
2017-08-07 957b8e9d4bc63524dad27c2f8458856da0bf5c06
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package com.clj.fastble.scan;
 
import android.bluetooth.BluetoothDevice;
import android.text.TextUtils;
 
import com.clj.fastble.data.ScanResult;
 
import java.util.concurrent.atomic.AtomicBoolean;
 
/**
 * scan a known name device, then connect
 */
public abstract class NameScanCallback extends PeriodScanCallback {
 
    private String mName = null;
    private String[] mNames = null;
    private boolean mFuzzy = false;
    private AtomicBoolean hasFound = new AtomicBoolean(false);
 
    public NameScanCallback(String name, long timeoutMillis, boolean fuzzy) {
        super(timeoutMillis);
        this.mName = name;
        this.mFuzzy = fuzzy;
        if (TextUtils.isEmpty(name)) {
            onDeviceNotFound();
        }
    }
 
    public NameScanCallback(String[] names, long timeoutMillis, boolean fuzzy) {
        super(timeoutMillis);
        this.mNames = names;
        this.mFuzzy = fuzzy;
        if (names == null || names.length < 1) {
            onDeviceNotFound();
        }
    }
 
    @Override
    public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
        if (device == null)
            return;
 
        if (TextUtils.isEmpty(device.getName())) {
            return;
        }
 
        if (!hasFound.get()) {
 
            ScanResult scanResult = new ScanResult(device, rssi, scanRecord,
                    System.currentTimeMillis());
 
            if (mName != null) {
                if (mFuzzy ? device.getName().contains(mName) : mName.equalsIgnoreCase(device.getName())) {
                    hasFound.set(true);
                    bleBluetooth.stopScan(NameScanCallback.this);
                    onDeviceFound(scanResult);
                }
            } else if (mNames != null) {
                for (String name : mNames) {
                    if (mFuzzy ? device.getName().contains(name) : name.equalsIgnoreCase(device.getName())) {
                        hasFound.set(true);
                        bleBluetooth.stopScan(NameScanCallback.this);
                        onDeviceFound(scanResult);
                        return;
                    }
                }
            }
        }
    }
 
    @Override
    public void onScanTimeout() {
        onDeviceNotFound();
    }
 
    @Override
    public void onScanCancel() {
 
    }
 
    public abstract void onDeviceFound(ScanResult sanResult);
 
    public abstract void onDeviceNotFound();
}