1. package cn.madfinger.core;
  2. import java.io.IOException;
  3. import java.lang.reflect.Method;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.util.UUID;
  7. import android.app.Activity;
  8. import android.bluetooth.BluetoothAdapter;
  9. import android.bluetooth.BluetoothDevice;
  10. import android.bluetooth.BluetoothSocket;
  11. import android.content.BroadcastReceiver;
  12. import android.content.Context;
  13. import android.content.Intent;
  14. import android.content.IntentFilter;
  15. import android.os.Bundle;
  16. import android.util.Log;
  17. import android.view.View;
  18. import android.widget.AdapterView;
  19. import android.widget.ArrayAdapter;
  20. import android.widget.Button;
  21. import android.widget.ListView;
  22. import android.widget.Toast;
  23. import android.widget.ToggleButton;
  24. public class BlueToothTestActivity extends Activity {
  25. //该UUID表示串口服务
  26. //请参考文章<a href="http://wiley.iteye.com/blog/1179417">http://wiley.iteye.com/blog/1179417</a>
  27. static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
  28. Button btnSearch, btnDis, btnExit;
  29. ToggleButton tbtnSwitch;
  30. ListView lvBTDevices;
  31. ArrayAdapter<String> adtDevices;
  32. List<String> lstDevices = new ArrayList<String>();
  33. BluetoothAdapter btAdapt;
  34. public static BluetoothSocket btSocket;
  35. @Override
  36. public void onCreate(Bundle savedInstanceState) {
  37. super.onCreate(savedInstanceState);
  38. setContentView(R.layout.main);
  39. // Button 设置
  40. btnSearch = (Button) this.findViewById(R.id.btnSearch);
  41. btnSearch.setOnClickListener(new ClickEvent());
  42. btnExit = (Button) this.findViewById(R.id.btnExit);
  43. btnExit.setOnClickListener(new ClickEvent());
  44. btnDis = (Button) this.findViewById(R.id.btnDis);
  45. btnDis.setOnClickListener(new ClickEvent());
  46. // ToogleButton设置
  47. tbtnSwitch = (ToggleButton) this.findViewById(R.id.tbtnSwitch);
  48. tbtnSwitch.setOnClickListener(new ClickEvent());
  49. // ListView及其数据源 适配器
  50. lvBTDevices = (ListView) this.findViewById(R.id.lvDevices);
  51. adtDevices = new ArrayAdapter<String>(this,
  52. android.R.layout.simple_list_item_1, lstDevices);
  53. lvBTDevices.setAdapter(adtDevices);
  54. lvBTDevices.setOnItemClickListener(new ItemClickEvent());
  55. btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能
  56. // ========================================================
  57. // modified by wiley
  58. /*
  59. * if (btAdapt.getState() == BluetoothAdapter.STATE_OFF)// 读取蓝牙状态并显示
  60. * tbtnSwitch.setChecked(false); else if (btAdapt.getState() ==
  61. * BluetoothAdapter.STATE_ON) tbtnSwitch.setChecked(true);
  62. */
  63. if (btAdapt.isEnabled()) {
  64. tbtnSwitch.setChecked(false);
  65. } else {
  66. tbtnSwitch.setChecked(true);
  67. }
  68. // ============================================================
  69. // 注册Receiver来获取蓝牙设备相关的结果
  70. IntentFilter intent = new IntentFilter();
  71. intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果
  72. intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
  73. intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
  74. intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
  75. registerReceiver(searchDevices, intent);
  76. }
  77. private BroadcastReceiver searchDevices = new BroadcastReceiver() {
  78. public void onReceive(Context context, Intent intent) {
  79. String action = intent.getAction();
  80. Bundle b = intent.getExtras();
  81. Object[] lstName = b.keySet().toArray();
  82. // 显示所有收到的消息及其细节
  83. for (int i = 0; i < lstName.length; i++) {
  84. String keyName = lstName[i].toString();
  85. Log.e(keyName, String.valueOf(b.get(keyName)));
  86. }
  87. BluetoothDevice device = null;
  88. // 搜索设备时,取得设备的MAC地址
  89. if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  90. device = intent
  91. .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  92. if (device.getBondState() == BluetoothDevice.BOND_NONE) {
  93. String str = "未配对|" + device.getName() + "|"
  94. + device.getAddress();
  95. if (lstDevices.indexOf(str) == -1)// 防止重复添加
  96. lstDevices.add(str); // 获取设备名称和mac地址
  97. adtDevices.notifyDataSetChanged();
  98. }
  99. }else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
  100. device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  101. switch (device.getBondState()) {
  102. case BluetoothDevice.BOND_BONDING:
  103. Log.d("BlueToothTestActivity", "正在配对......");
  104. break;
  105. case BluetoothDevice.BOND_BONDED:
  106. Log.d("BlueToothTestActivity", "完成配对");
  107. connect(device);//连接设备
  108. break;
  109. case BluetoothDevice.BOND_NONE:
  110. Log.d("BlueToothTestActivity", "取消配对");
  111. default:
  112. break;
  113. }
  114. }
  115. }
  116. };
  117. @Override
  118. protected void onDestroy() {
  119. this.unregisterReceiver(searchDevices);
  120. super.onDestroy();
  121. android.os.Process.killProcess(android.os.Process.myPid());
  122. }
  123. class ItemClickEvent implements AdapterView.OnItemClickListener {
  124. @Override
  125. public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
  126. long arg3) {
  127. if(btAdapt.isDiscovering())btAdapt.cancelDiscovery();
  128. String str = lstDevices.get(arg2);
  129. String[] values = str.split("\\|");
  130. String address = values[2];
  131. Log.e("address", values[2]);
  132. BluetoothDevice btDev = btAdapt.getRemoteDevice(address);
  133. try {
  134. Boolean returnValue = false;
  135. if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
  136. //利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice);
  137. Method createBondMethod = BluetoothDevice.class
  138. .getMethod("createBond");
  139. Log.d("BlueToothTestActivity", "开始配对");
  140. returnValue = (Boolean) createBondMethod.invoke(btDev);
  141. }else if(btDev.getBondState() == BluetoothDevice.BOND_BONDED){
  142. connect(btDev);
  143. }
  144. } catch (Exception e) {
  145. e.printStackTrace();
  146. }
  147. }
  148. }
  149. private void connect(BluetoothDevice btDev) {
  150. UUID uuid = UUID.fromString(SPP_UUID);
  151. try {
  152. btSocket = btDev.createRfcommSocketToServiceRecord(uuid);
  153. Log.d("BlueToothTestActivity", "开始连接...");
  154. btSocket.connect();
  155. } catch (IOException e) {
  156. // TODO Auto-generated catch block
  157. e.printStackTrace();
  158. }
  159. }
  160. class ClickEvent implements View.OnClickListener {
  161. @Override
  162. public void onClick(View v) {
  163. if (v == btnSearch)// 搜索蓝牙设备,在BroadcastReceiver显示结果
  164. {
  165. if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没开启
  166. Toast.makeText(BlueToothTestActivity.this, "请先打开蓝牙", 1000)
  167. .show();
  168. return;
  169. }
  170. if (btAdapt.isDiscovering())
  171. btAdapt.cancelDiscovery();
  172. lstDevices.clear();
  173. Object[] lstDevice = btAdapt.getBondedDevices().toArray();
  174. for (int i = 0; i < lstDevice.length; i++) {
  175. BluetoothDevice device = (BluetoothDevice) lstDevice[i];
  176. String str = "已配对|" + device.getName() + "|"
  177. + device.getAddress();
  178. lstDevices.add(str); // 获取设备名称和mac地址
  179. adtDevices.notifyDataSetChanged();
  180. }
  181. setTitle("本机蓝牙地址:" + btAdapt.getAddress());
  182. btAdapt.startDiscovery();
  183. } else if (v == tbtnSwitch) {// 本机蓝牙启动/关闭
  184. if (tbtnSwitch.isChecked() == false)
  185. btAdapt.enable();
  186. else if (tbtnSwitch.isChecked() == true)
  187. btAdapt.disable();
  188. } else if (v == btnDis)// 本机可以被搜索
  189. {
  190. Intent discoverableIntent = new Intent(
  191. BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  192. discoverableIntent.putExtra(
  193. BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
  194. startActivity(discoverableIntent);
  195. } else if (v == btnExit) {
  196. try {
  197. if (btSocket != null)
  198. btSocket.close();
  199. } catch (IOException e) {
  200. e.printStackTrace();
  201. }
  202. BlueToothTestActivity.this.finish();
  203. }
  204. }
  205. }
  206. }

最新文章

  1. 将程序部署到weblogic出现乱码问题
  2. App测试时,区分客户端或服务器端导致问题产生的方法
  3. [转]CSS,font-family,常用网页字体
  4. Tips10:你可以像写文档一样自由的复制粘贴游戏组件(Game Object Component)
  5. 洛谷U5653 宋荣子的小饼干
  6. 搭建高性能计算环境(二)、远程登录Linux服务器
  7. 【转】让 cocos2d-x 的 CCHttpRequest 支持https
  8. Header:请求头参数详解
  9. libctemplate——C语言模块引擎简介及使用
  10. CSS权威指南学习笔记系列(1)CSS和文档
  11. &#39;adb&#39; 不是内部或外部命令,也不是可运行的程序
  12. Rsync、Unison及DRBD的比较
  13. KoaHub平台基于Node.js开发的Koa JWT认证插件代码信息详情
  14. 使用MD5SUM检查文件
  15. .net EF之CodeFirst代码先行(转)
  16. webstrom
  17. List Leave
  18. 反向代理/负载均衡/session/cookie
  19. Sprign中常用注解
  20. MYSQL体系结构-来自期刊

热门文章

  1. mybatis自己主动生成mapper,dao,映射文件
  2. python-excel操作之xlrd
  3. css3--简单的加载动画
  4. module.exports,exports和export default,export的区别
  5. POJ 1474 Video Surveillance 半平面交/多边形核是否存在
  6. BZOJ1835: [ZJOI2010]base 基站选址(线段树优化Dp)
  7. Java生产者与消费者(下)
  8. Wget使用
  9. 測试CPU支持指令集AVX,AVX2,SSE情况的代码【VS2010调试通过】
  10. 阿姆达尔定律(Amdahl's law)