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 val BLE_SCAN_PERIOD : Long = 10000
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?>()
private lateinit var bleScanHandler:Handler 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()
}
bleScanHandler = Handler()
//蓝牙管理,这是系统服务可以通过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)
bleScanner.startScan(bleScanCallback)
Toast.makeText(this.applicationContext, "蓝牙BLE扫描开始", Toast.LENGTH_SHORT).show()
bleScanHandler.postDelayed(bleStopScan, this.BLE_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() {
var resultOfScan = resultMap
private var context: Context? = null fun setContext(context: Context) {
this.context = context
} 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()
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_BLUETOOTH_TURN_ON->{
when (resultCode) {
RESULT_OK->{
Toast.makeText(this.applicationContext, "蓝牙开启成功", Toast.LENGTH_SHORT).show()
bleStartScan.run()
}
RESULT_CANCELED->{
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)
}
}
}
Android 6.0 Kotlin 蓝牙BLE扫描的更多相关文章
- Android 6.0 Kotlin 蓝牙BLE扫描(改为指定时间没有发现新设备后停止扫描使用interface)
package com.arci.myapplication import android.os.Bundleimport android.support.design.widget.Snackbar ...
- Android 6.0 Kotlin 蓝牙扫描
package com.arci.myapplication import android.app.Activityimport android.os.Bundleimport android.sup ...
- android BluetoothAdapter蓝牙BLE扫描总结
1.android 4.3.1(Build.VERSION_CODES.JELLY_BEAN_MR2)增加的startLeScan(callback)方法,官方在5.0之后不建议使用,实测此方法,4. ...
- Android Studio3.0 Kotlin工程问题集
问题1: 新建支持Kotlin的Android项目,卡在"Resolve dependency :classpath" 解决分析: 一般碰到"Resolve depend ...
- [安卓] 20、基于蓝牙BLE的广播包高频快速搜索
前言: 之前介绍过很多蓝牙beacon.搜索.连接.通讯的文章.不过最近我发现:之前写的蓝牙广播包搜索的工程,搜索频率太慢,而且不能一直保持搜索状态.因此,这里探讨下高频蓝牙广播包扫描 -- 蓝牙BL ...
- Android网络开发之蓝牙
蓝牙采用分散式网络结构以及快调频和短包技术,支持点对点及点对多点通信,工作在全球通用的2.4GHz ISM(I-工业.S-科学.M-医学)频段,其数据速率为1Mbps,采用时分双工传输方案. 蓝牙 ...
- Android BLE与终端通信(五)——Google API BLE4.0低功耗蓝牙文档解读之案例初探
Android BLE与终端通信(五)--Google API BLE4.0低功耗蓝牙文档解读之案例初探 算下来很久没有写BLE的博文了,上家的技术都快忘记了,所以赶紧读了一遍Google的API顺便 ...
- Android蓝牙BLE开发,扫描、连接、发送和读取信息;
1.BLE开发权限 Android蓝牙BLE开发须打开蓝牙权限和6.0位置权限: <uses-permission android:name="android.permission.B ...
- 使用BleLib的轻松搞定Android低功耗蓝牙Ble 4.0开发具体解释
转载请注明来源: http://blog.csdn.net/kjunchen/article/details/50909410 使用BleLib的轻松搞定Android低功耗蓝牙Ble 4.0开发具体 ...
随机推荐
- 嵌入式开发之示波器----tektronix tds2024 的使用
http://jingyan.baidu.com/article/91f5db1bf715c01c7f05e39a.html http://cn.tek.com/learning/oscillosco ...
- HDU-1095-A+B for Input-Output Practice (VII)(多一个空格?)
A+B for Input-Output Practice (VII) Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32 ...
- Lumen rule
之前写了了laravel表单验证的生命周期:https://www.cnblogs.com/cxscode/p/7561277.html 今天来总结一下lumen的Validator的一些使用心得 可 ...
- 分布式服务框架dubbo入门实例
dubbo是一个分布式的服务架构,可直接用于生产环境作为SOA服务框架. 官网首页:http://dubbo.io/ ,官方用户指南 http://dubbo.io/User+Guide-zh.htm ...
- shop++源码反编译----随笔
一.applicationContext-mvc.xml配置 1.读取配置文件 <context:property-placeholder location="classpath*:/ ...
- E71自带铃声下载
NOKIA-e71 E71系统自带铃声下载,有几个听着不错~ E71铃声下载
- Canvas-三角函数曲线图
以本图为例,要做这张图,需要一些数学知识(三角函数sin,cos),有canvas的基础知识 Html <!DOCTYPE html> <html> <head> ...
- Python全栈day24-25(面向对象编程)
参考文档: http://www.cnblogs.com/linhaifeng/articles/6182264.html# 类:把一类事物的相同的特征和动作整合到一起就是类,类是抽象的概练 对象:就 ...
- python框架Scrapy中crawlSpider的使用——爬取内容写进MySQL
一.先在MySQL中创建test数据库,和相应的site数据表 二.创建Scrapy工程 #scrapy startproject 工程名 scrapy startproject demo4 三.进入 ...
- Python IDLE或shell中切换路径
在Python自带的编辑器IDLE中或者python shell中不能使用cd命令,那么跳到目标路径呢.方法是使用os包下的相关函数实现路径切换功能. import os os.getcwd() # ...