LeScanner прекращает сканирование через 1 минуту при запуске на переднем плане службыAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 LeScanner прекращает сканирование через 1 минуту при запуске на переднем плане службы

Сообщение Anonymous »

Я хочу, чтобы сканер Ble Beacon Scanner работал на переднем плане, не открывая пользовательский интерфейс приложения. Но когда я запускаю службу и выхожу из приложения (но не закрываю приложение), сканирование просто выполняется в течение 1 минуты и останавливается, но после того, как я снова открываю приложение, сканирование продолжается. Служба не отключается при закрытии приложения, а просто прекращает сканирование.

Код: Выделить всё

class BleForegroundService: Service() {
companion object {
private const val CHANNEL_ID = "ble_scanner_channel"
internal val TAG = BleForegroundService::class.java.simpleName
}

private lateinit var bluetoothManager: BluetoothManager
private lateinit var bluetoothAdapter: BluetoothAdapter
private lateinit var bluetoothLeScanner: BluetoothLeScanner
private val scanSettings = ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build()
private var scannedDevice: Int = 0

private var scanFilter = arrayListOf()

private val leScanCallback = BleScanCallback { result ->
Log.d(TAG, "Result : $result")
scannedDevice++
}

override fun onBind(p0: Intent?): IBinder? {
return null
}

override fun onCreate() {
super.onCreate()
val notification = createNotification()
startForeground(1, notification)

Log.d(TAG, "Creating BleForegroundScanner")
bluetoothManager = getSystemService(BluetoothManager::class.java)
bluetoothAdapter = bluetoothManager.adapter
bluetoothLeScanner = bluetoothAdapter.bluetoothLeScanner

val addressFilter = ScanFilter.Builder()
.setDeviceAddress("E3:C4:8D:05:54:CF")
.build()

scanFilter.add(addressFilter)
}

@SuppressLint("MissingPermission")
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d(TAG, "Starting Scanner")
bluetoothLeScanner.startScan(scanFilter, scanSettings, leScanCallback)

return START_NOT_STICKY
}

@SuppressLint("MissingPermission")
override fun onDestroy() {
Log.d(TAG, "Destroying BleForegroundScanner")
bluetoothLeScanner.stopScan(leScanCallback)
super.onDestroy()
}

private fun createNotification(): Notification {
val notificationChannelId = CHANNEL_ID

// depending on the Android API that we're dealing with we will have
// to use a specific method to create the notification
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(
notificationChannelId,
"Endless Service notifications channel",
NotificationManager.IMPORTANCE_HIGH
).let {
it.description = "Endless Service channel"
it.enableLights(true)
it.lightColor = Color.RED
it.enableVibration(true)
it.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
it
}
notificationManager.createNotificationChannel(channel)
}

val pendingIntent: PendingIntent = Intent(this, MainActivity::class.java).let { notificationIntent ->
PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE)
}

val builder: Notification.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) Notification.Builder(
this,
notificationChannelId
) else Notification.Builder(this)

return builder
.setContentTitle("BLE Beacon Scanner")
.setContentText("Scanning for BLE beacons")
.setContentIntent(pendingIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.setTicker("Ticker text")
.setPriority(Notification.PRIORITY_HIGH) // for under android 26 compatibility
.build()
}
}
И это внутри MainActivity я написал вот так, чтобы запустить службу на переднем плане

Код: Выделить всё

serviceIntent = Intent(this, BleForegroundService::class.java)
this.startForegroundService(serviceIntent)
Я не знаю, в чем проблема, почему сканирование длится всего 1 минуту и ​​прекращает сканирование. Но сервис не убит.

Подробнее здесь: https://stackoverflow.com/questions/792 ... nd-service
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»