实例介绍
【实例简介】
【实例截图】
【核心代码】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 | package com.managesoft.nullchen.buletoothdemo; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import static android.widget.Toast.LENGTH_SHORT; public class BuletoothClientActivity extends Activity implements OnItemClickListener{ // 获取到蓝牙适配器 private BluetoothAdapter mBluetoothAdapter; // 用来保存搜索到的设备信息 private List<String> bluetoothDevices = new ArrayList<String>(); // ListView组件 private ListView lvDevices; // ListView的字符串数组适配器 private ArrayAdapter<String> arrayAdapter; // UUID,蓝牙建立链接需要的 private final UUID MY_UUID = UUID .fromString( "00001101-0000-1000-8000-00805F9B34FB" ); // 为其链接创建一个名称 private final String NAME = "Bluetooth_Socket" ; // 选中发送数据的蓝牙设备,全局变量,否则连接在方法执行完就结束了 private BluetoothDevice selectDevice; // 获取到选中设备的客户端串口,全局变量,否则连接在方法执行完就结束了 private BluetoothSocket clientSocket; // 获取到向设备写的输出流,全局变量,否则连接在方法执行完就结束了 private OutputStream os; // 服务端利用线程不断接受客户端信息 private AcceptThread thread; //定义按钮 //定义按钮 private Button close_all_led; private Button red1 = null ; private Button green1 = null ; private Button blue1 = null ; private Button breath = null ; private TextView receive1; private SeekBar seekBar; private String LED_STATE = "A 红灯亮" ; private TextView re_msg; private TextView temperature; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.layout_buletooth_seacher); red1 = (Button)findViewById(R.id.red); green1 = (Button)findViewById(R.id.green); blue1 = (Button)findViewById(R.id.blue); receive1 = (TextView)findViewById(R.id.receive_text); close_all_led = (Button)findViewById(R.id.close_all_led); breath = (Button)findViewById(R.id.breath); seekBar = (SeekBar)findViewById(R.id.seekBar); re_msg = (TextView)findViewById(R.id.msg); temperature = (TextView)findViewById(R.id.temperature); red1.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { LED_STATE = "R" ; receive1.setText(LED_STATE); } }); green1.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { LED_STATE = "G" ; receive1.setText(LED_STATE); } }); blue1.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { LED_STATE = "B" ; receive1.setText(LED_STATE); } }); close_all_led.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { LED_STATE = "E" ; receive1.setText(LED_STATE); } }); breath.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { LED_STATE = "H" ; receive1.setText(LED_STATE); } }); seekBar.setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { if (b){ LED_STATE = "{0:" i "}" ; receive1.setText(LED_STATE); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); // 获取到蓝牙默认的适配器 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // 获取到ListView组件 lvDevices = (ListView) findViewById(R.id.lvDevices); // 为listview设置字符换数组适配器 arrayAdapter = new ArrayAdapter<String>( this , android.R.layout.simple_list_item_1, android.R.id.text1, bluetoothDevices); // 为listView绑定适配器 lvDevices.setAdapter(arrayAdapter); // 为listView设置item点击事件侦听 lvDevices.setOnItemClickListener( this ); // 用Set集合保持已绑定的设备 将绑定的设备添加到Set集合。 Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices(); if (devices.size() > 0 ) { for (BluetoothDevice bluetoothDevice : devices) { // 保存到arrayList集合中 bluetoothDevices.add(bluetoothDevice.getName() ":" bluetoothDevice.getAddress() "\n" ); } } // 因为蓝牙搜索到设备和完成搜索都是通过广播来告诉其他应用的 // 这里注册找到设备和完成搜索广播 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); registerReceiver(receiver, filter); filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(receiver, filter); // 实例接收客户端传过来的数据线程 thread = new AcceptThread(); // 线程开始 thread.start(); } //搜索蓝牙设备 public void onClick_Search(View view) { setTitle( "正在扫描..." ); // 点击搜索周边设备,如果正在搜索,则暂停搜索 if (mBluetoothAdapter.isDiscovering()) { mBluetoothAdapter.cancelDiscovery(); } mBluetoothAdapter.startDiscovery(); } // 注册广播接收者 private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context arg0, Intent intent) { // 获取到广播的action String action = intent.getAction(); // 判断广播是搜索到设备还是搜索完成 if (action.equals(BluetoothDevice.ACTION_FOUND)) { // 找到设备后获取其设备 BluetoothDevice device = intent .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // 判断这个设备是否是之前已经绑定过了,如果是则不需要添加,在程序初始化的时候已经添加了 if (device.getBondState() != BluetoothDevice.BOND_BONDED) { // 设备没有绑定过,则将其保持到arrayList集合中 bluetoothDevices.add(device.getName() ":" device.getAddress() "\n" ); // 更新字符串数组适配器,将内容显示在listView中 arrayAdapter.notifyDataSetChanged(); } } else if (action .equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) { setTitle( "搜索完成" ); } } }; // 点击listView中的设备,传送数据 @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // 获取到这个设备的信息 String s = arrayAdapter.getItem(position); // 对其进行分割,获取到这个设备的地址 String address = s.substring(s.indexOf( ":" ) 1 ).trim(); Log.d( "TAG" ,address); // 判断当前是否还是正在搜索周边设备,如果是则暂停搜索 if (mBluetoothAdapter.isDiscovering()) { mBluetoothAdapter.cancelDiscovery(); } // 如果选择设备为空则代表还没有选择设备 if (selectDevice == null ) { //通过地址获取到该设备 selectDevice = mBluetoothAdapter.getRemoteDevice(address); } // 这里需要try catch一下,以防异常抛出 try { // 判断客户端接口是否为空 if (clientSocket == null ) { // 获取到客户端接口 clientSocket = selectDevice .createRfcommSocketToServiceRecord(MY_UUID); // 向服务端发送连接 clientSocket.connect(); // 获取到输出流,向外写数据 os = clientSocket.getOutputStream(); } // 判断是否拿到输出流 if (os != null ) { // 需要发送的信息 //String text = "我传过去了"; // 以utf-8的格式发送出去 os.write(LED_STATE.getBytes( "UTF-8" )); } // 吐司一下,告诉用户发送成功 Toast.makeText( this , "发送信息成功,请查收" , LENGTH_SHORT).show(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); // 如果发生异常则告诉用户发送失败 Toast.makeText( this , "发送信息失败" , LENGTH_SHORT).show(); } } public void send(String string){ try { // 判断客户端接口是否为空 if (clientSocket == null ) { // 获取到客户端接口 clientSocket = selectDevice .createRfcommSocketToServiceRecord(MY_UUID); // 向服务端发送连接 clientSocket.connect(); // 获取到输出流,向外写数据 os = clientSocket.getOutputStream(); } // 判断是否拿到输出流 if (os != null ) { // 需要发送的信息 //String text = "我传过去了"; // 以utf-8的格式发送出去 os.write(string.getBytes( "UTF-8" )); } // 吐司一下,告诉用户发送成功 Toast.makeText( this , "发送信息成功,请查收" , LENGTH_SHORT).show(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); // 如果发生异常则告诉用户发送失败 Toast.makeText( this , "发送信息失败" , LENGTH_SHORT).show(); } } // 创建handler,因为我们接收是采用线程来接收的,在线程中无法操作UI,所以需要handler Handler handler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super .handleMessage(msg); // 通过msg传递过来的信息,吐司一下收到的信息 // Toast.makeText(BuletoothClientActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show(); re_msg.setText((String)msg.obj); //当检测到是要求接收温度时,发送数据 if (((String)msg.obj).equals( "R" )){ send( "当前温度:25.2 ℃" ); } } }; // 服务端接收信息线程 private class AcceptThread extends Thread { private BluetoothServerSocket serverSocket; // 服务端接口 private BluetoothSocket socket; // 获取到客户端的接口 private InputStream is; // 获取到输入流 private OutputStream os; // 获取到输出流 public AcceptThread() { try { // 通过UUID监听请求,然后获取到对应的服务端接口 serverSocket = mBluetoothAdapter .listenUsingRfcommWithServiceRecord(NAME, MY_UUID); } catch (Exception e) { e.printStackTrace(); } } public void run() { try { // 接收其客户端的接口 socket = serverSocket.accept(); // 获取到输入流 is = socket.getInputStream(); // 获取到输出流 os = socket.getOutputStream(); // 无线循环来接收数据 while ( true ) { // 创建一个128字节的缓冲 byte [] buffer = new byte [ 128 ]; // 每次读取128字节,并保存其读取的角标 int count = is.read(buffer); // 创建Message类,向handler发送数据 Message msg = new Message(); // 发送一个String的数据,让他向上转型为obj类型 msg.obj = new String(buffer, 0 , count, "utf-8" ); // 发送数据 handler.sendMessage(msg); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } } } |
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论