Android蓝牙连接实现

Android蓝牙连接实现,第1张

概述1、蓝牙权限2、打开蓝牙,有三种方式3、搜索蓝牙前6.0以上需开启动态权限、如下:privatevoidrequestPermission(){if(Build.VERSION.SDK_INT>=23){intcheckAccessFinePermission=ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS

1、蓝牙权限

2、打开蓝牙,有三种方式

3、搜索蓝牙前6.0以上需开启动态权限、如下:

private voID requestPermission() {    if (Build.VERSION.SDK_INT >= 23) {        int checkAccessFinePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);        if (checkAccessFinePermission != PackageManager.PERMISSION_GRANTED) {            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},                    REQUEST_PERMISSION_ACCESS_LOCATION);            Log.e(getPackagename(), "没有权限,请求权限");            return;        }        Log.e(getPackagename(), "已有定位权限");        search();    }}@OverrIDepublic voID onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {    switch (requestCode) {        case 1: {            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {                Log.e(getPackagename(), "开启权限permission granted!");                //做下面该做的事                search();            } else {                Log.e(getPackagename(), "没有定位权限,请先开启!");            }        }    }    super.onRequestPermissionsResult(requestCode, permissions, grantResults);}public voID search() {    if (bluetoothAdapter.isdiscovering())        bluetoothAdapter.canceldiscovery();    bluetoothAdapter.startdiscovery();    Log.e(getPackagename(), "开始搜索");}

4、注册广播去接收已搜索的蓝牙设备

//注册广播IntentFilter intentFilter = new IntentFilter();intentFilter.addAction(BluetoothDevice.ACTION_FOUND);intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);registerReceiver(new BluetoothReceiver(), intentFilter); 
class BluetoothReceiver extends broadcastReceiver {    @OverrIDe    public voID onReceive(Context context, Intent intent) {        if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)) {            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);            boolean addFlag = true;            for (BluetoothDevice bluetoothDevice : strArr) {                if (device.getAddress().equals(bluetoothDevice.getAddress())) {                    addFlag = false;                }            }            if (addFlag) {                if(device.getname() != null)                strArr.add(device);                adapter.notifyDataSetChanged();            }        } else if (intent.getAction().equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);            switch (device.getBondState()) {                case BluetoothDevice.BOND_NONE:                    Log.e(getPackagename(), "取消配对");                    break;                case BluetoothDevice.BOND_BONDING:                    Log.e(getPackagename(), "配对中");                    break;                case BluetoothDevice.BOND_BONDED:                    Log.e(getPackagename(), "配对成功");                    break;            }        }    }}

5、与设备配对、与设备解除配对

//与设备配对private voID bond(int i) {    try {        Method method = BluetoothDevice.class.getmethod("createBond");        Log.e(getPackagename(), "开始配对");        method.invoke(notStrArr.get(i));    } catch (Exception e) {        e.printstacktrace();    }}/** * 与设备解除配对 */private voID removeBonds(int i) {    try {        Method removeBondMethod = BluetoothDevice.class.getmethod("removeBond");        Log.e(getPackagename(), "解除配对");        removeBondMethod.invoke(strArr.get(i));    } catch (Exception e) {        e.printstacktrace();    }}

6、获取已绑定设备和已连接设备,如下:

/** * 获取已绑定和已连接设备 */public voID getBindDevice() {    Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();    if (strArr != null) {        strArr.clear();    }    strArr.addAll(bondedDevices);    connectDevicesAdapter.notifyDataSetChanged();}

7、获取已连接设备

/** * 获取已连接设备 */private voID getConnectedBtDevice() {    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象    try {        //得到连接状态的方法        Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);        //打开权限        method.setAccessible(true);        int state = (int) method.invoke(bluetoothAdapter, (Object[]) null);        if (state == BluetoothAdapter.STATE_CONNECTED) {            Log.i("BLUetoOTH", "BluetoothAdapter.STATE_CONNECTED");            Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices(); //集合里面包括已绑定的设备和已连接的设备            Log.i("BLUetoOTH", "devices:" + devices.size());            for (BluetoothDevice device : devices) {                Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);                method.setAccessible(true);                boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);                if (isConnected) { //根据状态来区分是已连接的还是已绑定的,isConnected为true表示是已连接状态。                    Log.i("BLUetoOTH-dh", "connected:" + device.getname());                }             }        }    } catch (Exception e) {        e.printstacktrace();    }}

好了,按照上面布置基本上可以实现蓝牙连接功能,有些细节问题需要自己去处理,就不一一解释了,谢谢你们的观赏!

总结

以上是内存溢出为你收集整理的Android蓝牙连接实现全部内容,希望文章能够帮你解决Android蓝牙连接实现所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

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

原文地址: http://outofmemory.cn/web/999703.html

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

发表评论

登录后才能评论

评论列表(0条)

保存