android开发之蓝牙初步 扫描已配对蓝牙、更改蓝牙可见性、搜索外部蓝牙设备

这两天我学习了android蓝牙的一些简单操作,今天和大家分享一下。

一,获得BluetoothAdapter对象

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

二,判断当前设备中是否有蓝牙设备

if(adapter!=null){
      //有蓝牙设备
     }else{
      //没有蓝牙设备
     }

三,判断蓝牙是否打开和打开蓝牙

 

if(adapter.isEnabled()){
    //BluetoothAdapter.ACTION_REQUEST_ENABLE为启动蓝牙的action
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivity(intent);
   }


 

四,得到所有已经配对蓝牙设备地址

	Set<BluetoothDevice> devices = adapter.getBondedDevices();
					if(devices.size()>0){
						for(Iterator iterator = devices.iterator();iterator.hasNext();){
							BluetoothDevice device = (BluetoothDevice) iterator.next();
							System.out.println("已配对的设备:"+device.getAddress());
						}
					}

五,设置蓝牙的可见性

//启动修改蓝牙可见性的Intent
					Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
					//设置蓝牙可见性的时间,方法本身规定最多可见300秒
					intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
					startActivity(intent);

六,扫描周围的蓝牙设备

adapter.startDiscovery();

android把扫描到的蓝牙设备通过广播的形式发出去,所以想接收扫描结果就必须写个广播接收器类。

  class BlutetoothReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			//从收到的intent对象中将代表远程蓝牙设配器的对象取出
			BluetoothDevice devices = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			System.out.println(devices.getAddress());
		}
    	
    }

七,注意事项:权限

注意:模拟器上不能模拟蓝牙设备,只能在真机上才能看到结果。

 <!-- 使用蓝牙设备的权限 -->
    <uses-permission android:name="android.permission.BLURTOOTH"/>
     <!-- 管理蓝牙设备的权限 -->
    <uses-permission android:name="android.permission.BLURTOOTH_ADMIN"/>


 

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值