在Android Studio中配对蓝牙设备

在Android Studio中配对蓝牙设备,第1张

在Android Studio中配对蓝牙设备

首次请求

BLUETOOTH_ADMIN
权限。

然后使您的设备可发现:

private void makeDiscoverable() {        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);        startActivity(discoverableIntent);        Log.i("Log", "Discoverable ");    }

然后创建一个 BroadcastReceiver监听系统中的动作:

private BroadcastReceiver myReceiver = new BroadcastReceiver() {        @Override        public void onReceive(Context context, Intent intent) { Message msg = Message.obtain(); String action = intent.getAction(); if(BluetoothDevice.ACTION_FOUND.equals(action)){    //Found, add to a device list }        }    };

并通过注册以下 BoardcastReceiver 开始搜索设备:

 private void startSearching() {        Log.i("Log", "in the start searching method");        IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);        BluetoothDemo.this.registerReceiver(myReceiver, intentFilter);        bluetoothAdapter.startDiscovery();    }

设备从 BroadcastReceiver 进入列表后,从列表中选择设备,并

createBond()
执行以下 *** 作:

 public boolean createBond(BluetoothDevice btDevice)      throws Exception      {         Class class1 = Class.forName("android.bluetooth.BluetoothDevice");        Method createBondMethod = class1.getMethod("createBond");          Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);          return returnValue.booleanValue();      }

Then use your pre above to manage with bonded devices.



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5498710.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存