BluetoothDevice蓝牙类详解

一. BluetoothDevice简介

1. 继承关系

[java]  view plain copy
  1. public static Class BluetoothDevice extends Object implement Parcelable  

该类实现了Parcelable接口, 实现了Parcelable接口的类的对象可以封装到Parcel对象中, 封装后的数据可以通过Intent或者IPC传递;


实现Parcelable接口要点 : 

a. 实现writeTpParcl()方法 : 将数据写入到Parcel对象中;

[java]  view plain copy
  1. public void writeToParcel(Parcel out, int arg1)   
  2. {   
  3.      // TODO Auto-generated method stub   
  4.      out.writeBundle(this.mBundle);   
  5. }  

b. 实现describeContents()方法 : 

[java]  view plain copy
  1. public int describeContents()   
  2. {   
  3.         // TODO Auto-generated method stub   
  4.         return 0;   
  5. }  

c.实现Parcelable.Creator接口 : 

[java] 
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android连接蓝牙需要使用蓝牙适配器(BluetoothAdapter)和蓝牙设备(BluetoothDevice)来实现。下面是一个简单的连接蓝牙的工具: 首先,需要在AndroidManifest.xml文件中添加蓝牙权限: <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> 然后,在工具中,我们首先要获取蓝牙适配器的实例: BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); 接下来,需要进行蓝牙的开启操作: if (!adapter.isEnabled()) { Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBluetooth, REQUEST_ENABLE_BT); } 当蓝牙开启成功后,我们可以进行设备的扫描操作: adapter.startDiscovery(); 然后,可以注册BroadcastReceiver来监听扫描结果和连接状态的改变: private final BroadcastReceiver mReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { // 扫描到新设备 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // 连接设备 connectDevice(device); } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { // 扫描结束 } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) { // 连接断开 } else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) { // 连接成功 } } }; 在connectDevice()方法中,可以使用BluetoothSocket来建立与设备的连接: BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID); socket.connect(); 最后,记得在Activity的onDestroy()方法中取消扫描和注销BroadcastReceiver: adapter.cancelDiscovery(); unregisterReceiver(mReceiver); 通过实现这些步骤,就可以实现Android连接蓝牙的功能了。当连接成功或断开时,我们可以对蓝牙设备进行数据的发送和接收操作。同时,还可以通过蓝牙Socket实现文件传输和音频传输等功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值