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
import android.os.Looper
import android.os.Message class MainActivity : AppCompatActivity() {
private val BLE_SCAN_PERIOD : Long = 10000
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 lateinit var bleScanHandler: Handler
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()
}
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.setNewScanResultListener(object : bleNewScanResultListener {
override fun onNewScanResult(scanResult: ScanResult?) {
TextView1.text = scanResult?.device?.name + ": " + scanResult?.device?.address
Handler(Looper.getMainLooper()).post {
Toast.makeText(this@MainActivity, scanResult?.device?.name + ": " + scanResult?.device?.address, Toast.LENGTH_SHORT).show()
}
bleScanHandler.removeCallbacks(bleStopScan)
bleScanHandler.postDelayed(bleStopScan, BLE_SCAN_PERIOD)
}
});
//
Toast.makeText(this.applicationContext, "蓝牙BLE扫描开始", Toast.LENGTH_SHORT).show()
bleScanner.startScan(bleScanCallback)
bleScanHandler.postDelayed(bleStopScan, BLE_SCAN_PERIOD)
} private val bleStopScan = Runnable {
bleScanner.stopScan(bleScanCallback)
Toast.makeText(this.applicationContext, "蓝牙BLE扫描结束", Toast.LENGTH_SHORT).show()
} //定义接口
interface bleNewScanResultListener {
fun onNewScanResult(scanResult: ScanResult?)
} class BleScanCallback(resultMap: MutableMap<String?, BluetoothDevice?>) : ScanCallback() {
private var resultOfScan = resultMap
var listener: bleNewScanResultListener? = null fun setNewScanResultListener(listener: bleNewScanResultListener) {
this.listener = listener
} 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) { } private fun addScanResult(scanResult: ScanResult?) {
val bleDevice = scanResult?.device
val deviceAddress = bleDevice?.address
if (!resultOfScan.contains(deviceAddress)) {
resultOfScan.put(deviceAddress, bleDevice)
this.listener?.onNewScanResult(scanResult)
}
}
}
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)
}
}
}

最新文章

  1. spring mvc文件上传(单个文件上传|多个文件上传)
  2. ASP对XML的增、删、改、查
  3. 【MongoDB初识】-安装篇
  4. 全球首个全流程跨平台界面开发套件,PowerUI分析
  5. SoapUI之webservice接口测试(一)
  6. iOS开发 - 网络数据安全加密(MD5)
  7. 钓鱼 贪心 end
  8. IO笔记
  9. Yii2的相关学习记录,前后台分离及migrate使用(七)
  10. C# 面向对象 , 抽象基类
  11. Linux入门之常用命令(2)
  12. Day9 操作系统介绍
  13. Lumen框架使用Redis与框架Cache压测比较
  14. LeetCode 559 Maximum Depth of N-ary Tree 解题报告
  15. centos5 升级到centos6
  16. 《Spring实战》-- &#39;cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element&#39; 错误的解决办法
  17. 【内核】内核链表使用说明,list.h注释
  18. c数据结构第一个公式写程序计算给定多项式在给定点x处的值
  19. zero-shor learning 数据集
  20. 八、cent OS下tomcat启用APR并发模式

热门文章

  1. input取值
  2. Visual Studio 2012/2010/2008 远程调试
  3. 网易研发project师(移动端游戏)—暑期实习生电面题目 2014年5月14日
  4. oracle11g卸载,10g之类版本通用
  5. 添加RichEdit控件后导致MFC对话框程序无法运行的解决方法
  6. Oracle体系机构
  7. Python_selenium之窗口切换
  8. iOS开发之--storyboary下,为btn/lab/view等添加裁剪和阴影的方法
  9. css 中的事件冒泡
  10. 跳出NSDate