I'm developing a android app using ble. I want schedule a scan every 10 second. It work but when my device is in background, it doesn't work.
in Oncreate() i call StartHandler();
public class MyService extends Service{
......
....
public void StartHandler(){
handlerScan = new Handler();
handlerScan.postDelayed(new Runnable() {
public void run() {
if (!STOP) {
scanLeDevice(true);
handlerScan.postDelayed(this, 8000);
}else{
handlerScan.postDelayed(this, 3000);
}
}
}, 500);
}
and scanLeDevice from Google
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);
}
}
- This is work when device is not in sleep. I have tried to use AlarmManager but the minimum time period for repeating alarm is 1 minute.
- TimerTask doesn't work in sleep mode.
- Handler doesn't work in sleep mode.
I Thought use WakeLock but if i acquire it here:
public void StartHandler(){
handlerScan = new Handler();
handlerScan.postDelayed(new Runnable() {
public void run() {
if (!STOP) {
wakelock.acquire();
scanLeDevice(true);
handlerScan.postDelayed(this, 8000);
}else{
handlerScan.postDelayed(this, 3000);
}
}
}, 500);
}
and release my wakelock in scanLeDevice
public void run() {
mScanning = false;
wakelock.release();
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
It work only first time. In various post i have read: "is not possibile acquire wakelock and release for for multiple times". Thank you.