android 蓝牙模块学习
2016-06-07 19:18
483 查看
1.今天学习了一天的Android 蓝牙基础,写点总结,看了一天感觉也是蛮累的.
遇到的问题: 学习的Android 官方的 聊天 demo ,这里讲几个需要理解的地方.
1> UUID 这个唯一识别码,在Android 中 需要靠他来建立连接,作为一种key ,通过他来匹配service端的socket端口
2> 自定义连接需要两个手机同时连接,一个连接成功关闭服务端,有了一个socket,可以通过这个socket 获取相应的输入输出流,进行数据通信.
3>建立套接字的时候尽量开启线程.
难点就是了解蓝牙的API,学会将不变的代码和变的代码分离,后面直接贴代码.
2>显示广播的基本处理方法,每个人处理方式不一样,逻辑而已
3>判断是否打开蓝牙,和获取已经绑定的设备
4>创建蓝牙的服务端,开启线程等待获取连接,连接成功后关闭,思考如果多对一的话,服务端是否不能关闭?
5>设置可见性
6>客户端连接
代码没有相关整理感觉很乱,实在不好意思.还要继续学习好封装
给一个Android demo 里面的例子了
遇到的问题: 学习的Android 官方的 聊天 demo ,这里讲几个需要理解的地方.
1> UUID 这个唯一识别码,在Android 中 需要靠他来建立连接,作为一种key ,通过他来匹配service端的socket端口
2> 自定义连接需要两个手机同时连接,一个连接成功关闭服务端,有了一个socket,可以通过这个socket 获取相应的输入输出流,进行数据通信.
3>建立套接字的时候尽量开启线程.
难点就是了解蓝牙的API,学会将不变的代码和变的代码分离,后面直接贴代码.
这里写代码片 1> ** 注册广播接收蓝牙各种状态的改变,从而来做相应的处理 action 需要自己去API // 创建一个IntentFilter对象,将其action指定为BluetoothDevice.ACTION_FOUND // IntentFilter它是一个过滤器,只有符合过滤器的Intent才会被我们的BluetoothReceiver所接收 IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); // 创建一个BluetoothReceiver对象 bluetoothReceiver = new BluetoothReceiver(); // 注册广播接收器 注册完后每次发送广播后,BluetoothReceiver就可以接收到这个广播了 registerReceiver(bluetoothReceiver, intentFilter);
2>显示广播的基本处理方法,每个人处理方式不一样,逻辑而已
// 接收广播 private class BluetoothReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Bundle b = intent.getExtras(); Object[] lstName = b.keySet().toArray(); // 显示所有收到的消息及其细节 for (int i = 0; i < lstName.length; i++) { String keyName = lstName[i].toString(); Log.e(keyName, String.valueOf(b.get(keyName))); } BluetoothDevice device = null; // 搜索设备时,取得设备的MAC地址 if (BluetoothDevice.ACTION_FOUND.equals(action)) { device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getBondState() == BluetoothDevice.BOND_NONE) { String str = "未配对|" + device.getName() + "|" + device.getAddress(); list.add(str); } } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); switch (device.getBondState()) { case BluetoothDevice.BOND_BONDING: Log.d("BlueToothTestActivity", "正在配对......"); break; case BluetoothDevice.BOND_BONDED: Log.d("BlueToothTestActivity", "完成配对"); connect(device);// 连接设备 break; case BluetoothDevice.BOND_NONE: Log.d("BlueToothTestActivity", "取消配对"); default: break; } } if (BluetoothDevice.ACTION_FOUND.equals(action)) { // 只要BluetoothReceiver接收到来自于系统的广播,这个广播是什么呢,是我找到了一个远程蓝牙设备 // Intent代表刚刚发现远程蓝牙设备适配器的对象,可以从收到的Intent对象取出一些信息 BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Toast.makeText(MainActivity.this, bluetoothDevice.getName(), Toast.LENGTH_SHORT).show(); Log.d("mytag", bluetoothDevice.getAddress()); switch (bluetoothDevice.getBondState()) { case BluetoothDevice.BOND_BONDING: Log.d("BlueToothTestActivity", "正在配对......"); break; case BluetoothDevice.BOND_BONDED: // 连接之前取消搜索周围的状态 blueAdapter.cancelDiscovery(); Toast.makeText(MainActivity.this, "正在配对蓝牙适配设备", Toast.LENGTH_LONG).show(); Log.d("BlueToothTestActivity", "完成配对"); connect(bluetoothDevice);// 连接设备 break; case BluetoothDevice.BOND_NONE: Log.d("BlueToothTestActivity", "取消配对"); default: break; } list.add(bluetoothDevice.getAddress()); list1.add(bluetoothDevice); } adapter.notifyDataSetChanged(); } }
3>判断是否打开蓝牙,和获取已经绑定的设备
// 表示存在蓝牙适配设备,判断蓝牙设备是否可用 if (!blueAdapter.isEnabled()) { // 调用代开蓝牙的权限 Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivity(intent); } Set<BluetoothDevice> list_devices = blueAdapter.getBondedDevices(); System.out.println("list_device------->size" + list_devices.size()); if (list_devices.size() > 0) { Iterator<BluetoothDevice> iterator = list_devices.iterator(); while (iterator.hasNext()) { BluetoothDevice device = iterator.next(); Log.i("device_address", device.getAddress()); list.add(device.getAddress()); list1.add(device); } } else { Toast.makeText(this, "没有连接的蓝牙设备", Toast.LENGTH_LONG).show(); }
4>创建蓝牙的服务端,开启线程等待获取连接,连接成功后关闭,思考如果多对一的话,服务端是否不能关闭?
private class AcceptThread extends Thread { private final BluetoothServerSocket mmServerSocket; public AcceptThread() { // Use a temporary object that is later assigned to mmServerSocket, // because mmServerSocket is final BluetoothServerSocket tmp = null; try { // MY_UUID is the app's UUID string, also used by the client code tmp = blueAdapter.listenUsingRfcommWithServiceRecord("Fisrt", uuid); } catch (IOException e) { } mmServerSocket = tmp; } public void run() { BluetoothSocket socket = null; // Keep listening until exception occurs or a socket is returned while (isRun) { try { socket = mmServerSocket.accept(); runOnUiThread( new Runnable() { public void run() { Toast.makeText(MainActivity.this, "connect sucess", Toast.LENGTH_LONG).show(); } }); } catch (IOException e) { break; } // If a connection was accepted if (socket != null) { // Do work to manage the connection (in a separate thread) try { isRun=false; mmServerSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; } } } /** Will cancel the listening socket, and cause the thread to finish */ public void cancel() { try { mmServerSocket.close(); } catch (IOException e) { } } }
5>设置可见性
// 通过Intent 设置可见性 系统默认时间最大值是300秒,500设置的值也是300而已. Intent intent_see = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); intent_see.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500); startActivity(intent_see);
6>客户端连接
private void connect(BluetoothDevice btDev) { Method creMethod; try { creMethod = BluetoothDevice.class .getMethod("createBond"); creMethod.invoke(btDev); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } try { Toast.makeText(this, "开始连接... ", Toast.LENGTH_SHORT).show(); btSocket = btDev.createRfcommSocketToServiceRecord(uuid); System.out.println("========" + "start connect"); Log.d("BlueToothTestActivity", "开始连接...");//注意需要关闭搜索 btSocket.connect(); Toast.makeText(this, "开始连接success ", Toast.LENGTH_SHORT).show(); } catch (IOException e) { // TODO Auto-generated catch block try { btSocket.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println(e.toString()); Toast.makeText(this, "connect failed ", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } }
代码没有相关整理感觉很乱,实在不好意思.还要继续学习好封装
给一个Android demo 里面的例子了
package com.svasan.bluetoothmmochatroom; import java.util.Set; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; /** * 蓝牙连接的主要封装类 * @author Administrator * */ public class MBluetoothDevice { // BluetoothAdapter actions public final String Action_Bluetooth_On = BluetoothAdapter.ACTION_REQUEST_ENABLE; public final String Action_Bluetooth_Discoverable = BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE; public final String Action_Bluetooth_Discovery_Finish=BluetoothAdapter.ACTION_DISCOVERY_FINISHED; // Bluetooth scan mode public final int Mode_Connectable_Discoverable = BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE; // BluetoothAdapter data public final String Data_Dicoverable=BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION; // Local Bluetooth adapter private BluetoothAdapter mBluetoothAdapter = null; public MBluetoothDevice() { // Get local Bluetooth adapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); } /* 判断本地手机是否支持蓝牙服务 */ public boolean isPhoneDevice_Support() { if (mBluetoothAdapter == null) return false; return true; } /* 判断本地手机是否开启蓝牙服务 */ public boolean isBluetoothAdapter_Enable() { return mBluetoothAdapter.isEnabled(); } /* 判断是否正在搜索中 */ public boolean isBluetooth_discovering() { return mBluetoothAdapter.isDiscovering(); } /* 获取搜索扫描模式 */ public int getBluetoothScanMode() { return mBluetoothAdapter.getScanMode(); } /*得到匹配项*/ public Set<BluetoothDevice> getPairedDevices() { return mBluetoothAdapter.getBondedDevices(); } /*获取蓝牙适配器*/ public BluetoothAdapter getBluetoothAdapter() { return mBluetoothAdapter; } public boolean discoveryBluetooth_Start() { return mBluetoothAdapter.startDiscovery(); } /*取消搜索*/ public void discoveryBluetooth_Cancel() { mBluetoothAdapter.cancelDiscovery(); } /*获取远程蓝牙设备对象*/ public BluetoothDevice getRomteBluetoothDevice(String address) { return mBluetoothAdapter.getRemoteDevice(address); } }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories