我有一个班级" ScanFunction.java "包含静态方法" startLeScan "扫描BLE设备。我想使用服务扫描BLE设备" BackgroundBleScanner "。我将扫描周期设置为2000毫秒。现在,我希望在延迟处理程序执行完毕后停止服务。
ScanFunction.java
public class ScanFunction {
private static final int SCAN_PERIOD = 2000;
private static ArrayList<byte[]> byteList;
private static Handler handler;
@TargetApi(21)
private static ScanCallback getLollipopCallback() {
ScanCallback callback = new ScanCallback() {
@Override
public void onScanFailed(int errorCode) {
Log.e("Lollipop Callback", "Error Code : " + errorCode);
}
@Override
public void onScanResult(int callbackType, ScanResult result) {
byte[] beacBytes = result.getScanRecord().getBytes();
Utilities.bytesToBeacon(beacBytes,result.getRssi()); //Function to fetch beacon UUID and store it in Application class
}
};
return callback;
}
@TargetApi(21)
private static void startLollipopScanner(BluetoothAdapter bluetoothAdapter){
final BluetoothLeScanner leScanner = bluetoothAdapter.getBluetoothLeScanner();
final ScanCallback callback = getLollipopCallback();
ScanSettings scanSettings = (new ScanSettings.Builder()).setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
List<ScanFilter> scanFilters=null;
handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
leScanner.stopScan(callback);
Utilities.sortBeaconsByRssi();
}
},SCAN_PERIOD);
leScanner.startScan(scanFilters,scanSettings,callback);
}
public static void startLeScan(BluetoothAdapter bluetoothAdapter){
//byteList.clear();
if(Build.VERSION.SDK_INT<21){
startJellyBeanScanner(bluetoothAdapter);
}
else if (Build.VERSION.SDK_INT>=21){
startLollipopScanner(bluetoothAdapter);
}
}
}
BackgroundBleScanner.java
public class BackgroundBleScanner extends Service {
BluetoothAdapter mBluetoothAdapter;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
if (mBluetoothAdapter != null || mBluetoothAdapter.isEnabled()){
ScanFunction.startLeScan(mBluetoothAdapter)
}
Intent i = new Intent(this,BackgroundBleScanner.class);
PendingIntent pi = PendingIntent.getService(this,12,i,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 9000,pi);
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("ondestroy","Service Destroyed");
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}