android开发之蓝牙主动配对连接手机
来源:互联网 发布:淘宝店铺正在被处罚 编辑:程序博客网 时间:2024/05/04 03:57
上一篇介绍了手机配对连接的三种方式,这篇以完整的一个代码实例介绍如何搜索周围的蓝牙设备,以及主动配对,连接。
主要注释在代码中都有。
[java] view plaincopyprint?
1 package jason.com;
2
3 import java.io.IOException;
4 import java.lang.reflect.Method;
5 import java.util.ArrayList;
6 import java.util.List;
7 import java.util.UUID;
8
9 import android.app.Activity;
10 import android.bluetooth.BluetoothAdapter;
11 import android.bluetooth.BluetoothDevice;
12 import android.bluetooth.BluetoothSocket;
13 import android.content.BroadcastReceiver;
14 import android.content.Context;
15 import android.content.Intent;
16 import android.content.IntentFilter;
17 import android.os.Bundle;
18 import android.util.Log;
19 import android.view.View;
20 import android.widget.AdapterView;
21 import android.widget.ArrayAdapter;
22 import android.widget.Button;
23 import android.widget.ListView;
24 import android.widget.Toast;
25 import android.widget.ToggleButton;
26
27 public class BlueToothTestActivity extends Activity {
28 //该UUID表示串口服务
29 static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
30 Button btnSearch, btnDis, btnExit;
31 ToggleButton tbtnSwitch;
32 ListView lvBTDevices;
33 ArrayAdapter<String> adtDevices;
34 List<String> lstDevices = new ArrayList<String>();
35 BluetoothAdapter btAdapt;
36 public static BluetoothSocket btSocket;
37
38 @Override
39 public void onCreate(Bundle savedInstanceState) {
40 super.onCreate(savedInstanceState);
41 setContentView(R.layout.main);
42 // Button 设置
43 btnSearch = (Button) this.findViewById(R.id.btnSearch);
44 btnSearch.setOnClickListener(new ClickEvent());
45 btnExit = (Button) this.findViewById(R.id.btnExit);
46 btnExit.setOnClickListener(new ClickEvent());
47 btnDis = (Button) this.findViewById(R.id.btnDis);
48 btnDis.setOnClickListener(new ClickEvent());
49
50 // ToogleButton设置
51 tbtnSwitch = (ToggleButton) this.findViewById(R.id.tbtnSwitch);
52 tbtnSwitch.setOnClickListener(new ClickEvent());
53
54 // ListView及其数据源 适配器
55 lvBTDevices = (ListView) this.findViewById(R.id.lvDevices);
56 adtDevices = new ArrayAdapter<String>(this,
57 android.R.layout.simple_list_item_1, lstDevices);
58 lvBTDevices.setAdapter(adtDevices);
59 lvBTDevices.setOnItemClickListener(new ItemClickEvent());
60
61 btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能
62
63 // ========================================================
64 // modified by jason0539 搜索jason0539进入我的博客
65 /*
66 * if (btAdapt.getState() == BluetoothAdapter.STATE_OFF)// 读取蓝牙状态并显示
67 * tbtnSwitch.setChecked(false); else if (btAdapt.getState() ==
68 * BluetoothAdapter.STATE_ON) tbtnSwitch.setChecked(true);
69 */
70 if (btAdapt.isEnabled()) {
71 tbtnSwitch.setChecked(false);
72 } else {
73 tbtnSwitch.setChecked(true);
74 }
75 // ============================================================
76 // 注册Receiver来获取蓝牙设备相关的结果
77 IntentFilter intent = new IntentFilter();
78 intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果
79 intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
80 intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
81 intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
82 registerReceiver(searchDevices, intent);
83 }
84
85 private BroadcastReceiver searchDevices = new BroadcastReceiver() {
86
87 public void onReceive(Context context, Intent intent) {
88 String action = intent.getAction();
89 Bundle b = intent.getExtras();
90 Object[] lstName = b.keySet().toArray();
91
92 // 显示所有收到的消息及其细节
93 for (int i = 0; i < lstName.length; i++) {
94 String keyName = lstName[i].toString();
95 Log.e(keyName, String.valueOf(b.get(keyName)));
96 }
97 BluetoothDevice device = null;
98 // 搜索设备时,取得设备的MAC地址
99 if (BluetoothDevice.ACTION_FOUND.equals(action)) {
100 device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
101 if (device.getBondState() == BluetoothDevice.BOND_NONE) {
102 String str = "未配对|" + device.getName() + "|"
103 + device.getAddress();
104 if (lstDevices.indexOf(str) == -1)// 防止重复添加
105 lstDevices.add(str); // 获取设备名称和mac地址
106 adtDevices.notifyDataSetChanged();
107 }
108 }else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
109 device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
110 switch (device.getBondState()) {
111 case BluetoothDevice.BOND_BONDING:
112 Log.d("BlueToothTestActivity", "正在配对......");
113 break;
114 case BluetoothDevice.BOND_BONDED:
115 Log.d("BlueToothTestActivity", "完成配对");
116 connect(device);//连接设备
117 break;
118 case BluetoothDevice.BOND_NONE:
119 Log.d("BlueToothTestActivity", "取消配对");
120 default:
121 break;
122 }
123 }
124
125 }
126 };
127
128 @Override
129 protected void onDestroy() {
130 this.unregisterReceiver(searchDevices);
131 super.onDestroy();
132 android.os.Process.killProcess(android.os.Process.myPid());
133 }
134
135 class ItemClickEvent implements AdapterView.OnItemClickListener {
136
137 @Override
138 public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
139 long arg3) {
140 if(btAdapt.isDiscovering()) btAdapt.cancelDiscovery();
141 String str = lstDevices.get(arg2);
142 String[] values = str.split("\\|");
143 String address = values[2];
144 Log.e("address", values[2]);
145 BluetoothDevice btDev = btAdapt.getRemoteDevice(address);
146 try {
147 Boolean returnValue = false;
148 if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
149 //利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice);
150 Method createBondMethod = BluetoothDevice.class
151 .getMethod("createBond");
152 Log.d("BlueToothTestActivity", "开始配对");
153 returnValue = (Boolean) createBondMethod.invoke(btDev);
154
155 }else if(btDev.getBondState() == BluetoothDevice.BOND_BONDED){
156 connect(btDev);
157 }
158 } catch (Exception e) {
159 e.printStackTrace();
160 }
161
162 }
163
164 }
165
166 private void connect(BluetoothDevice btDev) {
167 UUID uuid = UUID.fromString(SPP_UUID);
168 try {
169 btSocket = btDev.createRfcommSocketToServiceRecord(uuid);
170 Log.d("BlueToothTestActivity", "开始连接...");
171 btSocket.connect();
172 } catch (IOException e) {
173 // TODO Auto-generated catch block
174 e.printStackTrace();
175 }
176 }
177
178 class ClickEvent implements View.OnClickListener {
179 @Override
180 public void onClick(View v) {
181 if (v == btnSearch)// 搜索蓝牙设备,在BroadcastReceiver显示结果
182 {
183 if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没开启
184 Toast.makeText(BlueToothTestActivity.this, "请先打开蓝牙", 1000)
185 .show();
186 return;
187 }
188 if (btAdapt.isDiscovering())
189 btAdapt.cancelDiscovery();
190 lstDevices.clear();
191 Object[] lstDevice = btAdapt.getBondedDevices().toArray();
192 for (int i = 0; i < lstDevice.length; i++) {
193 BluetoothDevice device = (BluetoothDevice) lstDevice[i];
194 String str = "已配对|" + device.getName() + "|"
195 + device.getAddress();
196 lstDevices.add(str); // 获取设备名称和mac地址
197 adtDevices.notifyDataSetChanged();
198 }
199 setTitle("本机蓝牙地址:" + btAdapt.getAddress());
200 btAdapt.startDiscovery();
201 } else if (v == tbtnSwitch) {// 本机蓝牙启动/关闭
202 if (tbtnSwitch.isChecked() == false)
203 btAdapt.enable();
204
205 else if (tbtnSwitch.isChecked() == true)
206 btAdapt.disable();
207 } else if (v == btnDis)// 本机可以被搜索
208 {
209 Intent discoverableIntent = new Intent(
210 BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
211 discoverableIntent.putExtra(
212 BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
213 startActivity(discoverableIntent);
214 } else if (v == btnExit) {
215 try {
216 if (btSocket != null)
217 btSocket.close();
218 } catch (IOException e) {
219 e.printStackTrace();
220 }
221 BlueToothTestActivity.this.finish();
222 }
223 }
224
225 }
226 }
- android开发之蓝牙主动配对连接手机
- android开发之蓝牙主动配对连接手机
- android开发之蓝牙主动配对连接手机
- Android之蓝牙开发初编(发现蓝牙,配对蓝牙,连接蓝牙)
- android开发之蓝牙配对连接的方法
- android开发之蓝牙配对连接的方法
- android开发之蓝牙配对连接的方法
- android开发之蓝牙配对连接的方法
- Android 蓝牙开发之搜索、配对、连接、通信大全
- Android 蓝牙开发之搜索、配对、连接、通信大全
- Android 蓝牙开发之搜索、配对、连接、通信大全
- Android 蓝牙开发之搜索、配对、连接、通信大全
- Android 蓝牙开发之搜索、配对、连接、通信大全
- Android开发之蓝牙连接与配对设备
- android开发之蓝牙配对连接的方法
- Android 蓝牙开发之搜索、配对、连接、通信大全
- Android开发蓝牙篇之蓝牙配对、连接与接收数据
- android蓝牙主动发起配对实例
- iOS中多个StoryBoard的跳转问题
- 特大整数相加(C实现)
- 一个很好的源码下载学习网站
- 5.5 GDI 映射模式
- Pentaho Mondrian 教程(一)集成
- android开发之蓝牙主动配对连接手机
- 类型转换基础例子
- Eclipse 在开发中使用到的快捷键很实用噢(转载)
- hdu2045 不容易系列之(3)—— LELE的RPG难题 (动态规划)
- ntp时间服务器同步完整配置(ntp.sjtu.edu.cn 202.120.2.101 (上海交通大学网络中心NTP服务器地址))
- thinkphp——关于前台模板显示顶级栏目及其对应所有商品分页和二级栏目及对应的商品分页
- 非极大值抑制
- JAVA List 方法总结
- 杭电OJ题目分类