Use this class to start automatic to new BLE Devices.
BLEScanner Services
public class BLEScanner extends Service {
private BluetoothAdapter mBluetoothAdapter;
private ArrayList<BluetoothDevice> mLeDevices;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLeDevices = new ArrayList<BluetoothDevice>();
if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
}
startLeScan();
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void startLeScan() {
scanLeDevice(true);
}
private void stopLeScan() {
scanLeDevice(false);
}
private void scanLeDevice(boolean enable) {
if (enable) {
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
if (!mLeDevices.contains(device)) {
mLeDevices.add(device);
connectToDevice(device);
}
}
};
private void connectToDevice(final BluetoothDevice device) {
if (device != null) {
Log.i("Tag", "Name: " + device.getAddress() + " Connecting");
if (device.getName() != null)
device.connectGatt(this.getApplicationContext(), false, new BluetoothCallBack(this.getApplicationContext(), BLEScanner.this));
}
}
@Override
public void onDestroy() {
super.onDestroy();
stopLeScan();
mLeDevices.clear();
}
public void removeDevice(BluetoothDevice mDevice) {
try {
if (mLeDevices != null && mLeDevices.size() > 0)
mLeDevices.remove(mDevice);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now Callback Class to check BLE Device Connect or not
public class BluetoothCallBack extends BluetoothGattCallback {
private BLEScanner mServiceObject;
public BluetoothCallBack(Context mContext, BLEScanner mServiceObject) {
this.mServiceObject = mServiceObject;
}
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.i("Tag", "CONNECTED DEVICE: " + gatt.getDevice().getAddress());
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.e("Tag", "DISCONNECTED DEVICE: " + gatt.getDevice().getAddress());
gatt.disconnect();
gatt.close();
mServiceObject.removeDevice(gatt.getDevice());
}
}
}