Bluetooth的使用

来源:互联网 发布:石家庄软件学院 编辑:程序博客网 时间:2024/06/15 09:14

Bluetooth的使用分用以下几种:
1.蓝牙耳机:HeadSet
2.高效传输音频
3.连接健康设备:HealthDevice

  • Bluetooth使用的基本步骤:
1.在manifest中获得权限  <uses-permission android:name="android.permission.BLUETOOTH"/>//使用默认的蓝牙硬件的权限  <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>//对蓝牙硬件更改配置的权限2.获得默认的adapterbluetoothAdapter = BluetoothAdapter.getDefaultAdapter();3.查看蓝牙是否开启, if (!bluetoothAdapter.isEnabled()) {//如果得的默认的蓝牙adapter不可用则蓝牙设备没有开启  Intent startBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);   startActivityForResult(startBluetoothIntent, BLUETOOTH_REQUEST);//会开启一个DialogActivity来提供用户是否开启蓝牙如上图(1),通过onActivityResult中的ResultsCode==RESULT_OK来判断蓝牙是否开启了  }4.设置蓝牙的开放检测时间 //若蓝牙未开启则会开启如图(2)DialogActivity,若蓝牙已经开启则不会跳出DialogActivity  Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);  discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//设置蓝牙开放检测的时间,单位为秒,若设为0,则表示一直开放检测搜索  startActivity(discoverableIntent);4.设置Profile.ServiceListener对象,当蓝牙连接或断开时调用 private BluetoothProfile.ServiceListener profileListener = new BluetoothProfile.ServiceListener() {        @Override        public void onServiceConnected(int profile, BluetoothProfile proxy) {        //先判断profile的值            if (profile == BluetoothProfile.HEADSET) {                bluetoothHeadset = (BluetoothHeadset) proxy;            }        }        @Override        public void onServiceDisconnected(int profile) {            if (profile == BluetoothProfile.HEADSET) {                bluetoothHeadset = null;            }        }    };5.通过getProfileProxy()来建立与配置文件相关联的代理的连接bluetoothAdapter.getProfileProxy(this, profileListener, BluetoothProfile.HEADSET);//使用蓝牙耳机bluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, bluetoothHeadset);//关闭蓝牙耳机6.管理应用profile

这里写图片描述这里写图片描述

原创粉丝点击