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扫描的更多相关文章

  1. Android 6.0 Kotlin 蓝牙BLE扫描(改为指定时间没有发现新设备后停止扫描使用interface)

    package com.arci.myapplication import android.os.Bundleimport android.support.design.widget.Snackbar ...

  2. Android 6.0 Kotlin 蓝牙扫描

    package com.arci.myapplication import android.app.Activityimport android.os.Bundleimport android.sup ...

  3. android BluetoothAdapter蓝牙BLE扫描总结

    1.android 4.3.1(Build.VERSION_CODES.JELLY_BEAN_MR2)增加的startLeScan(callback)方法,官方在5.0之后不建议使用,实测此方法,4. ...

  4. Android Studio3.0 Kotlin工程问题集

    问题1: 新建支持Kotlin的Android项目,卡在"Resolve dependency :classpath" 解决分析: 一般碰到"Resolve depend ...

  5. [安卓] 20、基于蓝牙BLE的广播包高频快速搜索

    前言: 之前介绍过很多蓝牙beacon.搜索.连接.通讯的文章.不过最近我发现:之前写的蓝牙广播包搜索的工程,搜索频率太慢,而且不能一直保持搜索状态.因此,这里探讨下高频蓝牙广播包扫描 -- 蓝牙BL ...

  6. Android网络开发之蓝牙

    蓝牙采用分散式网络结构以及快调频和短包技术,支持点对点及点对多点通信,工作在全球通用的2.4GHz ISM(I-工业.S-科学.M-医学)频段,其数据速率为1Mbps,采用时分双工传输方案.   蓝牙 ...

  7. Android BLE与终端通信(五)——Google API BLE4.0低功耗蓝牙文档解读之案例初探

    Android BLE与终端通信(五)--Google API BLE4.0低功耗蓝牙文档解读之案例初探 算下来很久没有写BLE的博文了,上家的技术都快忘记了,所以赶紧读了一遍Google的API顺便 ...

  8. Android蓝牙BLE开发,扫描、连接、发送和读取信息;

    1.BLE开发权限 Android蓝牙BLE开发须打开蓝牙权限和6.0位置权限: <uses-permission android:name="android.permission.B ...

  9. 使用BleLib的轻松搞定Android低功耗蓝牙Ble 4.0开发具体解释

    转载请注明来源: http://blog.csdn.net/kjunchen/article/details/50909410 使用BleLib的轻松搞定Android低功耗蓝牙Ble 4.0开发具体 ...

随机推荐

  1. python zlib压缩存储到mysql列

    数据太大压缩存储,可以使用zlib中的压缩函数,代码如下: import ujson import MySQLdb import zlib import base64 kwargs = { 'host ...

  2. ES6快速入门使用

    https://www.jianshu.com/p/061304806bda Babel-webpack的配置 Bebal官方文档 前段项目我想使用ES6的语法我应该怎么做呢?我们可以查看Babel的 ...

  3. yum 安装出错--"Couldn't resolve host 'mirrors.aliyun.com'"

    1.yum 安装出错 [root@iz25m0z7ik3z ~]#yum install mysql [root@iZ25m0z7ik3Z ~]#yum install mysql Loaded pl ...

  4. Sql Server数据批量更新

    UPDATE S SET S.[name]=T.[name],S.[sch_id]=T.[sch_id],S.[sex]=T.[sex],S.[isOk]=T.[isOk] FROM [Student ...

  5. http文件导出

    using (MemoryStream file = db.ExportExcel(model)) { context.Response.ContentType = "application ...

  6. uva 465 - Overflow 高精度还是浮点数?

    uva 465 - Overflow  Overflow  Write a program that reads an expression consisting of two non-negativ ...

  7. <转载> C++笔试、面试笔记

    这些东西有点烦,有点无聊.如果要去C++面试就看看吧.几年前网上搜索的.刚才看到,就整理一下,里面有些被我改了,感觉之前说的不对或不完善. 1.求下面函数的返回值( 微软) int func(x)  ...

  8. hdu3729(二分图)

    比赛的时候没有想到二分图,一直在想dp和贪心. 原因是因为看到数据是100000所以直接就没有往二分图匹配上想. 现在想想. 因为二分图两边的太不对称了,60 和100000 , 如果用匈牙利算法考虑 ...

  9. Scrapy命令和备注

    Scrapy命令和备注 1.创建一个新项目(命令行) project是项目名 scrapy startproject <project_name> 2.调试项目(pycharm) 在pyc ...

  10. 160708、JQuery解析XML数据的demo

    用JavaScript解析XML数据是常见的编程任务,JavaScript能做的,JQuery当然也能做.下面我们来总结几个使用JQuery解析XML的例子. 方案1 当后台返回的数据类型是xml对象 ...