zoukankan      html  css  js  c++  java
  • Android 6.0 Kotlin 蓝牙BLE扫描(改为指定时间没有发现新设备后停止扫描)

    package com.arci.myapplication

    import android.os.Bundle
    import android.support.design.widget.Snackbar
    import android.support.v7.app.AppCompatActivity
    import android.view.Menu
    import android.view.MenuItem
    import android.view.View

    import kotlinx.android.synthetic.main.activity_main.*
    import kotlinx.android.synthetic.main.content_main.*
    import android.bluetooth.BluetoothManager
    import android.content.Context
    import android.bluetooth.BluetoothAdapter
    import android.widget.Toast
    import android.content.Intent
    import android.bluetooth.BluetoothDevice
    import android.bluetooth.le.BluetoothLeScanner
    import android.bluetooth.le.ScanCallback
    import android.bluetooth.le.ScanResult
    import android.os.Handler

    class MainActivity : AppCompatActivity() {
    private val REQUEST_BLUETOOTH_TURN_ON = 1
    private lateinit var bleAdapter: BluetoothAdapter
    private lateinit var bleManager: BluetoothManager
    private lateinit var bleScanner: BluetoothLeScanner
    private lateinit var bleScanCallback: BleScanCallback
    private var bleScanResults = mutableMapOf<String?, BluetoothDevice?>()

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setSupportActionBar(toolbar)

    fab.setOnClickListener { view ->
    Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
    .setAction("Action", null).show()
    }
    //蓝牙管理,这是系统服务可以通过getSystemService(BLUETOOTH_SERVICE)的方法获取实例
    bleManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
    //通过蓝牙管理实例获取适配器,然后通过扫描方法(scan)获取设备(device)
    bleAdapter = bleManager.adapter
    if (!bleAdapter.isEnabled) {
    val bluetoothTurnOn = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
    startActivityForResult(bluetoothTurnOn, REQUEST_BLUETOOTH_TURN_ON)
    } else {
    bleStartScan.run()
    }
    }

    //start scan
    private val bleStartScan = Runnable {
    bleScanner = bleAdapter.bluetoothLeScanner
    bleScanCallback = BleScanCallback(bleScanResults)
    bleScanCallback.setContext(this.applicationContext)
    bleScanCallback.setStopScan(this.bleStopScan)
    bleScanner.startScan(bleScanCallback)
    Toast.makeText(this.applicationContext, "蓝牙BLE扫描开始", Toast.LENGTH_SHORT).show()
    bleScanCallback.scanHandler.postDelayed(bleStopScan, bleScanCallback.SCAN_PERIOD)
    }

    private val bleStopScan = Runnable {
    if (bleScanner != null) {
    bleScanner.stopScan(bleScanCallback)
    }
    Toast.makeText(this.applicationContext, "蓝牙BLE扫描结束", Toast.LENGTH_SHORT).show()
    }

    class BleScanCallback(resultMap: MutableMap<String?, BluetoothDevice?>) : ScanCallback() {
    val SCAN_PERIOD : Long = 10000
    var resultOfScan = resultMap
    private var context: Context? = null
    private var stopScan: Runnable? = null
    var scanHandler = Handler()

    fun setContext(context: Context) {
    this.context = context
    }

    fun setStopScan(runnable: Runnable) {
    this.stopScan = runnable
    }

    override fun onScanResult(callbackType: Int, result: ScanResult?) {
    addScanResult(result)
    }

    override fun onBatchScanResults(results: MutableList<ScanResult>?) {
    results?.forEach { result -> addScanResult(result) }
    }

    override fun onScanFailed(errorCode: Int) {
    Toast.makeText(this.context, "蓝牙BLE扫描失败" + "Error Code: " + errorCode, Toast.LENGTH_SHORT).show()
    }

    fun addScanResult(scanResult: ScanResult?) {
    val bleDevice = scanResult?.device
    val deviceAddress = bleDevice?.address
    if (!resultOfScan.contains(deviceAddress)) {
    resultOfScan.put(deviceAddress, bleDevice)
    if (this.context != null) {
    Toast.makeText(this.context, bleDevice?.name + ": " + bleDevice?.address, Toast.LENGTH_SHORT).show()
    }
    this.scanHandler.removeCallbacks(this.stopScan)
    this.scanHandler.postDelayed(this.stopScan, this.SCAN_PERIOD)
    }
    }
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {
    REQUEST_BLUETOOTH_TURN_ON->{
    when (resultCode) {
    RESULT_OK->{
    //TextView1.text = "蓝牙开启成功"
    Toast.makeText(this.applicationContext, "蓝牙开启成功", Toast.LENGTH_SHORT).show()
    bleStartScan.run()
    }
    RESULT_CANCELED->{
    //TextView1.text = "蓝牙开启失败"
    Toast.makeText(this.applicationContext, "蓝牙开启失败", Toast.LENGTH_SHORT).show()
    }
    }
    }
    }
    }
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
    // Inflate the menu; this adds items to the action bar if it is present.
    menuInflater.inflate(R.menu.menu_main, menu)
    return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    return when (item.itemId) {
    R.id.action_settings -> true
    else -> super.onOptionsItemSelected(item)
    }
    }
    }
  • 相关阅读:
    html5储存篇(二)
    html5 存储篇(一)
    【刷题计划1】【poj分类转载】【8月20号开始】
    【如何搭建一个属于自己的独立博客~~~基于windows系统,使用wordpress建站】【弱菜一枚~~大神请路过】
    第六章 6.6 图的应用
    第六章 6.5 图的遍历
    第六章 6.4 图的存储结构
    poj 2488 A Knight's Journey 【dfs】【字典序】【刷题计划】
    【Educational Codeforces Round 33 B】Beautiful Divisors
    【 Educational Codeforces Round 33 A】Chess For Three
  • 原文地址:https://www.cnblogs.com/arci/p/8150049.html
Copyright © 2011-2022 走看看