Я хочу, чтобы сканер Ble Beacon Scanner работал на переднем плане, не открывая пользовательский интерфейс приложения. Но когда я запускаю службу и выхожу из приложения (но не закрываю приложение), сканирование просто выполняется в течение 1 минуты и останавливается, но после того, как я снова открываю приложение, сканирование продолжается. Служба не отключается при закрытии приложения, а просто прекращает сканирование.
Я хочу, чтобы сканер Ble Beacon Scanner работал на переднем плане, не открывая пользовательский интерфейс приложения. Но когда я запускаю службу и выхожу из приложения (но не закрываю приложение), сканирование просто выполняется в течение 1 минуты и останавливается, но после того, как я снова открываю приложение, сканирование продолжается. Служба не отключается при закрытии приложения, а просто прекращает сканирование. [code]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)
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 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() } } [/code] И это внутри MainActivity я написал вот так, чтобы запустить службу на переднем плане [code]serviceIntent = Intent(this, BleForegroundService::class.java) this.startForegroundService(serviceIntent) [/code] Я не знаю, в чем проблема, почему сканирование длится всего 1 минуту и прекращает сканирование. Но сервис не убит.