cloudroam
2025-02-14 2fce91b8c0faf1290d8a35ee022dab3cdbc28a54
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.example.firstapp.service
 
import android.Manifest
import android.app.Service
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.content.pm.PackageManager
import android.os.IBinder
import androidx.core.app.ActivityCompat
import com.example.firstapp.utils.ACTION_RESTART
import com.example.firstapp.utils.ACTION_START
import com.example.firstapp.utils.ACTION_STOP
import com.example.firstapp.utils.Log
//import com.example.firstapp.utils.task.TaskUtils
 
@Suppress("PrivatePropertyName", "DEPRECATION")
class BluetoothScanService : Service() {
 
    private val TAG: String = BluetoothScanService::class.java.simpleName
    private val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
 
    companion object {
        var isRunning = false
    }
 
    override fun onBind(p0: Intent?): IBinder? {
        return null
    }
 
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent == null) return START_NOT_STICKY
        Log.i(TAG, "onStartCommand: ${intent.action}")
 
        when (intent.action) {
            ACTION_START -> startDiscovery()
            ACTION_STOP -> stopDiscovery()
            ACTION_RESTART -> {
                stopDiscovery()
                startDiscovery()
            }
        }
        return START_NOT_STICKY
    }
 
    // 开始扫描蓝牙设备
    private fun startDiscovery() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
            return
        }
        if (isRunning) return
        // 清空已发现设备
//        TaskUtils.discoveredDevices = mutableMapOf()
        bluetoothAdapter?.startDiscovery()
        isRunning = true
    }
 
    // 停止蓝牙扫描
    private fun stopDiscovery() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
            return
        }
        if (!isRunning) return
        bluetoothAdapter?.cancelDiscovery()
        isRunning = false
    }
 
    override fun onDestroy() {
        super.onDestroy()
        isRunning = false
        stopDiscovery()
    }
 
}