1.网络权限
android:name="android.hardware.bluetooth_le" android:required="true" /> 打开蓝牙,两种方式,一种是询问式,一种是自动式 2.//注册广播 fun initbc(){ Log.e("TAG","开始注册蓝牙广播" ) //注册搜索结束广播 val finshed = IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED) registerReceiver(myreviver,finshed) //注册设备被发现时候的广播 val found = IntentFilter(BluetoothDevice.ACTION_FOUND) registerReceiver(myreviver,found) //注册蓝牙状态改变广播 val state = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED) registerReceiver(myreviver,state) } 3.广播类 class Mybro : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { Log.e("TAG","接收到广播") Log.e("TAG","广播内容:"+intent?.action) //判断广播Action,是不是蓝牙发送过来的广播 if(intent?.action==ACTION_FOUND){ //获取广播中的信息,蓝牙设备信息 val parcelableExtra : BluetoothDevice? =intent.getParcelableExtra //获取已经配对的设备 parcelableExtra?.let { listDevices?.add(it)} Log.e("ai","onReceive: " +listDevices) if(parcelableExtra?.bondState ==BOND_BONDED){ Log.e("TAG","当前已经配对蓝牙设备名称:"+ parcelableExtra?.name) Log.e("TAG","${parcelableExtra.uuids}当前已经配对蓝牙设备地址:"+ parcelableExtra?.address) Log.e("TAG","---------------------------------------------------") }else if(parcelableExtra?.bondState !=BOND_BONDED){ Log.e("TAG","当前没有配对蓝牙设备名称:"+ parcelableExtra?.name) Log.e("TAG","${parcelableExtra?.uuids}当前没有配对蓝牙设备地址:"+ parcelableExtra?.address) Log.e("TAG","---------------------------------------------------") } }else if(intent?.action == BluetoothAdapter.ACTION_DISCOVERY_FINISHED){ Log.e("TAG","蓝牙搜索结束") Log.e("TAG","搜索结束打印所有蓝牙设备"+listDevices ) }else if(intent?.action == BluetoothAdapter.ACTION_STATE_CHANGED){ Log.e("TAG","蓝牙状态发生改变") val intExtra =intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,0) // 蓝牙已经打开 if(intExtra == BluetoothAdapter.STATE_ON){ Log.e("TAG","蓝牙已经被打开,广播监听") //蓝牙关闭 }else if(intExtra == BluetoothAdapter.STATE_OFF){ Log.e("TAG","蓝牙已经被关闭,广播监听") } } } } 4.//开始搜索 fun inBule(){ descs=BluetoothAdapter.getDefaultAdapter() //判断当前蓝牙是否开启 if (descs.isEnabled){ seach() }else{ descs.enable() Toast.makeText(this,"蓝牙没有打开",Toast.LENGTH_SHORT).show() } } 5./** * 解决:无法发现蓝牙设备的问题 * * 对于发现新设备这个功能, 还需另外两个权限(Android M 以上版本需要显式获取授权,附授权代码): */ private val ACCESS_LOCATION =1 private fun getPermission() { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { var permissionCheck =0 permissionCheck = checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) permissionCheck += checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) if (permissionCheck != PackageManager.PERMISSION_GRANTED) { //未获得权限 requestPermissions( arrayOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION ), ACCESS_LOCATION )// 自定义常量,任意整型 } } } 6.蓝牙配对 val method: Method = BluetoothDevice::class.java.getMethod("createBond") Log.e(packageName,"开始配对") method.invoke(listDevices.get(position)) startActivity(Intent(this@MainActivity,PrintActivity::class.java)) 7.解除广播 override fun onDestroy() { super.onDestroy() // 解除广播注册 unregisterReceiver(myreviver) }