Я новичок android и пытаюсь создать приложение, которое подключается к устройству и взаимодействует с ним. Для подключения мне сначала нужно найти устройство, которое я делаю с помощью lescanner. Приложение работает нормально со старыми версиями android, но не запускает сканирование с новым android 10. У меня проблема в том, что я не могу отладить устройство из-за единственного телефона android 10, который я могу использовать, это не мое и не рядом со мной все время. Я видел, что есть другие с такой же проблемой на android 10, и их проблемы всегда были с разрешениями, которые я чувствую, я покрыл. Что я делаю неправильно? Я добавил все необходимые разрешения:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
Вот как я запрашиваю разрешения на onCreate:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (this.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.MyDialogTheme);
builder.setTitle("This app needs background location access");
builder.setMessage("Please grant location access so this app can detect your device in the background.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_REQUEST_BACKGROUND_LOCATION);
}
});
builder.show();
}
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.MyDialogTheme);
builder.setTitle("This app needs fine location and background location access");
builder.setMessage("Please grant location access so this app can detect your device.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_BACKGROUND_LOCATION},
PERMISSION_REQUEST_FINE_LOCATION);
}
});
builder.show();
}
}else
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Android M Permission check
if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.MyDialogTheme);
builder.setTitle("This app needs coarse location access");
builder.setMessage("Please grant location access so this app can detect your device.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
}
});
builder.show();
}
}else if (ContextCompat.checkSelfPermission(this,"android.permission.ACCESS_COARSE_LOCATION")
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
"android.permission.ACCESS_COARSE_LOCATION")) {
}else{
ActivityCompat.requestPermissions(this,
new String[]{"android.permission.ACCESS_COARSE_LOCATION"},1 );
}
}
А вот мой код для сканирования:
public void scanBTLEDevices ( final boolean enable){
if (mBluetoothAdapter == null || mBluetoothAdapter.getBluetoothLeScanner() == null) {
Log.d("BTLE", "Bluetooth adapter or scanner were null!");
return;
}
if (enable) {
Log.i(TAG, "scanBTLEDevices: Scanning started!");
List<ScanFilter> filters = new ArrayList<ScanFilter>();
filters.add(new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString("00001813-0000-1000-8000-00805f9b34fb")).build());
ScanSettings settings = new ScanSettings.Builder().setReportDelay(0).setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
mScanning = true;
mBluetoothAdapter.getBluetoothLeScanner().startScan(filters, settings,scanCallback);//filters, settings
Toast.makeText(this,"Scanning started",Toast.LENGTH_SHORT).show();
} else {
mScanning = false;
mBluetoothAdapter.getBluetoothLeScanner().stopScan(scanCallback);
Toast.makeText(this,"Scanning stopped",Toast.LENGTH_SHORT).show();
Log.i(TAG, "Scanning stopped");
}
}
private ScanCallback scanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
BluetoothDevice device = result.getDevice();
if (device.getName() == null) {
return;
}
Log.i(TAG,"Scanner found:"+device.getName());
Toast.makeText(getApplicationContext(),"Scanner found something",Toast.LENGTH_SHORT).show();
if(!scannedDevices.contains(device.getName()) && device.getName()!=null) {
if (device.getName().equals(DEVICE_NAME)) {
if (mBluetoothLeService != null) {
scanBTLEDevices(false);
mDeviceAddress = device.getAddress();
mBluetoothLeService.connect(mDeviceAddress);
}
}
}
}
@Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
switch (errorCode){
case ScanCallback.SCAN_FAILED_ALREADY_STARTED:
Log.i(TAG,"onScanFailed: SCAN_FAILED_ALREADY_STARTED");
case ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED:
Log.i(TAG, "onScanFailed: SCAN_FAILED_APPLICATION_REGISTRATION_FAILED");
case ScanCallback.SCAN_FAILED_FEATURE_UNSUPPORTED:
Log.i(TAG, "onScanFailed: SCAN_FAILED_FEATURE_UNSUPPORTED");
case ScanCallback.SCAN_FAILED_INTERNAL_ERROR:
Log.i(TAG, "onScanFailed: SCAN_FAILED_INTERNAL_ERROR");
default:
Log.i(TAG, "onScanFailed: unknown error code");
}
}
};