Code: Select all
interface ScanningStatus {
void setCurrentlyScanning(boolean updatedStatus);
boolean getCurrentlyScanning();
}
public class SettingsScanningViewModel extends AndroidViewModel {
private MutableLiveData mDeviceList;
private ArrayList mInternalDeviceList;
private MutableLiveData mIsScanning;
private static final String TAG = "viewmodel";
private BluetoothManager mBtManager;
private BluetoothAdapter mBtAdapter;
private BluetoothLeScanner mBleScanner;
private static final long SCAN_PERIOD = 5000;
public SettingsScanningViewModel(Application mApplication) {
super(mApplication);
mDeviceList = new MutableLiveData();
mInternalDeviceList = new ArrayList();
mIsScanning = new MutableLiveData();
mBtManager = (BluetoothManager) mApplication.getSystemService(Context.BLUETOOTH_SERVICE);
mBtAdapter = mBtManager.getAdapter();
mBleScanner = mBtAdapter.getBluetoothLeScanner();
}
MutableLiveData getBtDevices() {
return mDeviceList;
}
MutableLiveData getScanningStatus() {
return mIsScanning;
}
private void flushList() {
mInternalDeviceList.clear();
mDeviceList.setValue(mInternalDeviceList);
}
private void injectIntoList(BluetoothDevice btDevice) {
mInternalDeviceList.add(btDevice);
mDeviceList.setValue(mInternalDeviceList);
}
private ScanCallback scanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
Log.d(TAG, "in callback");
BluetoothDevice mDevice = result.getDevice();
if (!mInternalDeviceList.contains(mDevice) && mDevice.getName() != null) {
injectIntoList(mDevice);
}
}
@Override
public void onScanFailed(int errorCode) {
Log.d(TAG, "onScanFailed: " + errorCode);
}
};
private ScanningStatus scanningStatus = new ScanningStatus() {
@Override
public void setCurrentlyScanning(boolean status) {
mIsScanning.setValue(status);
}
public boolean getCurrentlyScanning() {
return mIsScanning.getValue();
}
};
void doBtScan() {
Log.d(TAG, "flush list first");
flushList();
Log.d(TAG, "starting scan with scanCallback " + scanCallback);
scanningStatus.setCurrentlyScanning(true);
mBleScanner.startScan(scanCallback);
Log.d(TAG, "scan should be running for " + SCAN_PERIOD);
Handler handler = new Handler();
handler.postDelayed(() -> {
mBleScanner.stopScan(scanCallback);
scanningStatus.setCurrentlyScanning(false);
}, SCAN_PERIOD);
}
}
< /code>
Ich bin mir wirklich nicht sicher, was falsch ist. Liegt es daran, dass ich in meinem ViewModel neue BluetoothManager
Danke.