扫描ble后,Android应用返回了0台设备

时间:2019-06-15 19:37:57

标签: android kotlin bluetooth-lowenergy android-bluetooth

在过去的几个月中,我一直在开发一个应用程序,该应用程序的功能实现从应用程序到设备的BLE连接。今天突然,经过几次扫描,尽管之前获得了5或6,该应用仍会每次返回0台设备。

我一直认为这是与粗略位置有关的权限问题,但是,我所做的更改很小,因此不应受到影响,但这没关系

当我遵循Google在其他指南中提供的bluetooth guide时,这是我的代码:

onCreate方法:

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_guide)
        handler = Handler()
        devicesResult = ArrayList()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {

            // Android M Permission check

            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
                {
                val builder = AlertDialog.Builder(this)
                builder.setTitle("This app needs location access")
                builder.setMessage("Please grant location access so this app can detect beacons.")
                builder.setPositiveButton(android.R.string.ok, null)
                builder.setOnDismissListener { requestPermissions(arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), PERMISSION_REQUEST_COARSE_LOCATION) }
                builder.show()
            }else{

                if (areLocationServicesEnabled(this))
                {

                    if (!packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE))
                    {
                        Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show()
                        finish()
                    }

                    bluetoothAdapter?.takeIf { it.isDisabled }?.apply {
                        val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                        startActivityForResult(enableBtIntent, 1)
                    }

                    //scanLeDevice(true)
                }
            }
        }
}

onRequestPermissionsResult方法:

override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>, grantResults: IntArray
    ) {
        when (requestCode) {
            PERMISSION_REQUEST_COARSE_LOCATION -> {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //Log.d(FragmentActivity.TAG, "coarse location permission granted")
                } else {
                    val builder = AlertDialog.Builder(this)
                    builder.setTitle("Functionality limited")
                    builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.")
                    builder.setPositiveButton(android.R.string.ok, null)
                    builder.setOnDismissListener { }
                    builder.show()
                }
                return
            }
        }
    }

areLocationServicesEnabled方法:

private fun areLocationServicesEnabled(context:Context):Boolean {
        val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        return try {
            locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
        } catch (e:Exception) {
            e.printStackTrace()
            false
        }
    }

onResume方法:

override fun onResume() {
        super.onResume()
        if (bluetoothAdapter != null && !bluetoothAdapter!!.isEnabled)
        {
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(enableBtIntent, 1)
        }

            mLEScanner = bluetoothAdapter!!.bluetoothLeScanner
            scanLeDevice(true)

    }

scanLeDevice方法:

private fun scanLeDevice(enable:Boolean) {
        if (enable)
        {
            handler!!.postDelayed({
                mLEScanner!!.stopScan(mScanCallback)

                //selectDevice()
            }, SCAN_PERIOD)
            mLEScanner!!.startScan(mScanCallback)
        }
        else
        {
            mLEScanner!!.stopScan(mScanCallback)
        }
    }

mScanCallback属性:

private val mScanCallback = object : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult) {
            Log.i("callbackType", callbackType.toString())
            Log.i("result", result.toString())
            devicesResult!!.add(result)


        }

        override fun onBatchScanResults(results: List<ScanResult>) {
            for (sr in results) {
                Log.i("ScanResult - Results", sr.toString())
            }
        }

        override fun onScanFailed(errorCode: Int) {
            Log.e("Scan Failed", "Error Code: $errorCode")
        }
    }

正如我之前所说,我希望每个设备都显示并保存在一个名为deviceResult的数组中,但是,突然之间,每次新扫描之后似乎都没有设备出现。

1 个答案:

答案 0 :(得分:0)

首先,对回答muy问题的耽搁感到抱歉。

在@Emil在我的问题的最后评论中尝试在30秒之间不使用扫描超过6次之后,我终于可以使我的项目正常工作了,谢谢@Emil。