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. }

android蓝牙主动发起配对实例的更多相关文章

  1. 如何实现android蓝牙开发 自动配对连接,并不弹出提示框

    之前做一个android版的蓝牙 与血压计通讯的项目,遇到最大的难题就是自动配对. 上网查资料说是用反射createBond()和setPin(),但测试时进行配对还是会出现提示,但配对是成功了 我就 ...

  2. Android 蓝牙开发之搜索、配对、连接、通信大全

            蓝牙( Bluetooth®):是一种无线技术标准,可实现固定设备.移动设备和楼宇个人域网之间的短距离数据 交换(使用2.4-2.485GHz的ISM波段的UHF无线电波).蓝牙设备最 ...

  3. Android蓝牙实例(和单片机蓝牙模块通信)

    最近做毕设,需要写一个简单的蓝牙APP进行交互,在网上也找了很多资料,终于给搞定了,这里分享一下^_^. 1.Android蓝牙编程 蓝牙3.0及以下版本编程需要使用UUID,UUID是通用唯一识别码 ...

  4. Android自己主动化測试之Monkeyrunner用法及实例

    眼下android SDK里自带的现成的測试工具有monkey 和 monkeyrunner两个.大家别看这俩兄弟名字相像,但事实上是完全然全不同的两个工具,应用在不同的測试领域.总的来说,monke ...

  5. Android蓝牙自动配对Demo,亲测好使!!!

    蓝牙自动配对,即搜索到其它蓝牙设备之后直接进行配对,不需要弹出配对确认框或者密钥输入框. 转载请注明出处http://blog.csdn.net/qq_25827845/article/details ...

  6. Android蓝牙自动配对Demo,亲测好使!!!(转)

    蓝牙自动配对,即搜索到其它蓝牙设备之后直接进行配对,不需要弹出配对确认框或者密钥输入框. 转载请注明出处http://blog.csdn.net/qq_25827845/article/details ...

  7. Android 蓝牙开发(整理大全)

    Android蓝牙开发 鉴于国内Android蓝牙开发的例子很少,以及蓝牙开发也比较少用到,所以找的资料不是很全. (一): 由于Android蓝牙的通信都需要用到UUID,如果由手机发起搜索,当搜索 ...

  8. Android蓝牙学习笔记

    一 Bluetooth基本概念 蓝牙是无线数据和语音传输的开放式标准,它将各种通信设备.计算机及其终端设备.各种数字数据系统.甚至家用电器采用无线方式联接起来.它的传输距离为10cm-10m,如果增加 ...

  9. Android 蓝牙4.0 BLE

    Android ble (Bluetooth Low Energy) 蓝牙4.0,也就是说API level >= 18,且支持蓝牙4.0的手机才可以使用. BLE是蓝牙4.0的核心Profil ...

随机推荐

  1. 【Codeforces Round #426 (Div. 2) C】The Meaningless Game

    [Link]:http://codeforces.com/contest/834/problem/C [Description] 有一个两人游戏游戏; 游戏包括多轮,每一轮都有一个数字k,赢的人把自己 ...

  2. C++的class的样例

    私有就是仅仅可以通过内部调用,在类外面是不可以使用私有成员的 简单的写一个  Class A {  public:    //你能够通过公有的函数去訪问私有成员    Demo()   //能够在这使 ...

  3. Problem C: Celebrity Split

    题目描写叙述 Problem C: Celebrity Split Jack and Jill have decided to separate and divide their property e ...

  4. css笔记(二)——几种经常使用的模式

    文本垂直居中 对于行内元素,height会自己主动收缩到包裹住文本的高度,所以不存在这个问题. 可是对于block和inline-block等盒子元素.假设设置了height属性,则文本默认会在上方显 ...

  5. 1.17 Python基础知识 - 迭代器和生成器初识

    可循环迭代的对象称为可迭代对象,迭代器和生成器函数是可迭代对象. 列表解析表达式:可以简单高效处理一个可迭代对象,并生成结果列表 示例代码: [ i ** 2 for i in range(10) ] ...

  6. BZOJ3530: [Sdoi2014]数数(Trie图,数位Dp)

    Description 我们称一个正整数N是幸运数,当且仅当它的十进制表示中不包含数字串集合S中任意一个元素作为其子串.例如当S=(22,333,0233)时,233是幸运数,2333.20233.3 ...

  7. CSRF Failed: Referer checking failed - no Referer

    postman模拟登录出了这个错误,其实看标题就知道大概是怎么回事,网上大概找了办法,也没说到位,所以干脆自己找源码了. 问题很明显就是出在 CSRF 上,理所当然去查看 CsrfViewMiddle ...

  8. MFC ClistCtr锁定隐藏某一列

    通过设置列的宽度为0, 可以隐藏列表框的某一列,但是用户通过拖动列表框的大小,隐藏的列,可能又被显示出来了. 我们可以自己写一个CListEx继承CListCtr,然后捕获拖动的消息,对该消息进行特殊 ...

  9. 【Codeforces Round #452 (Div. 2) A】 Splitting in Teams

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 贪心 1优先和2组队. 如果1没有了 就结束. 如果1还有多余的. 那么就自己3个3个组队 [代码] #include <bi ...

  10. POJ——T2271 Guardian of Decency

    http://poj.org/problem?id=2771 Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 5932   A ...