I have the following Service in Android
public class MyService extends Service{
....
@Override
public void onCreate() {
....
StartHandler();
....}
public void StartHandler(){
handlerScan = new Handler();
handlerScan.postDelayed(new Runnable() {
public void run() {
if (!STOP) {
scanLeDevice(true);
handlerScan.postDelayed(this, 8000);
}else{
mBluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
mBluetoothAdapter = mBluetoothManager.getAdapter();
handlerScan.postDelayed(this, 3000);
}
}
}, 500);
}
.....
public void scanLeDevice(final boolean enable) {
if(mLeScanCallback == null){
mBluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
mBluetoothAdapter = mBluetoothManager.getAdapter();
try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }
}
if (enable) {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}, 3000);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
....
Question: If i use API < 21 it works in background sometimes, but if i use new API > 21 (MLEScanner) when display is turned off it doesn't work. Why? Is this a bug?
Question: In my StartHandler I want acquire wakelock for 3 second and release. considers, StartHandler is repeated. Wakelock work only first time. How can solve this? There is a solution for acquire wakelock on startlescan and release this in stoplescan?
I don't want use AlarmManager why i need of a handler postdelayed. Thank you