public class BleScanUtil {
private static final String TAG ="BleScanUtil";
private BluetoothAdapter mBluetoothAdapter;
private boolean mIsScanning =false;
private BleScanI mBleScan;
public BleScanUtil(BleScanI bleScan) {
mBluetoothAdapter =BluetoothAdapter.getDefaultAdapter();
mBleScan = bleScan;
}
/**
* Start scan bluetooth device.
*/
public void startLeScan() {
Log.d(TAG, "Start Scan");
if (mBluetoothAdapter ==null) {
Log.d(TAG, "mBluetoothAdapter null");
return;
}
if (mIsScanning) {
Log.d(TAG, "Repeated scan");
return;
}
mIsScanning =true;
if (mBluetoothAdapter.startLeScan(mLeScanCallback)) {
handler.sendEmptyMessageDelayed(0, 10000);
}else {
mBleScan.onScanFail();
mIsScanning =false;
Log.d(TAG, "Scan fail");
}
}
private Handler handler =new BaseHandler(new BaseHandler.BaseHandlerCallBack() {
@Override
public void handlerCallBack(Message msg) {
stopScan();
}
});
private void stopScan() {
handler.removeMessages(0);
if (mIsScanning) {
mIsScanning =false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
mBleScan.onScanStop();
}
}
/**
* 打开蓝牙
* @param context 你懂的
*/
public void openBluetooth(Activity context) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
context.startActivityForResult(enableBtIntent, 1);
}
}
/**
* 是否支持ble
*/
public boolean isSupperBle(Context context) {
PackageManager manager = context.getPackageManager();
return manager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
}
//Scan callback
private BluetoothAdapter.LeScanCallback mLeScanCallback =new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(BluetoothDevice device, int arg1, byte[] arg2) {
Log.d(TAG, "Scanning");
if (device.getName() !=null) {
mBleScan.onScanReturn(device);
}
}
};
}
接口:
public interface BleScanI {
void onScanReturn(BluetoothDevice device);
void onScanStop();
void onScanFail();
}