java – 连接到Bluegiga WT-12的Android蓝牙聊天应用程序

前端之家收集整理的这篇文章主要介绍了java – 连接到Bluegiga WT-12的Android蓝牙聊天应用程序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想使用我们使用蓝牙聊天开源代码的蓝牙连接,但它在我的Eclipse上不起作用,因此经过一些更改后,它才能正常工作.现在我可以与Bluegiga WT-12聊天,通过串行电缆连接到PC. Bluegiga WT-12与BG Term连接(就像Hyperterminal一样).

只是想分享!我希望它能为开发人员提供相同的应用程序提供一些帮助. BlueChat与可用的相同.

这是BluetoothChatService代码编辑:

  1. package com.example.android.BluetoothChat;
  2. public class BluetoothChatService {
  3. // Debugging
  4. private static final String TAG = "BluetoothChatService";
  5. private static final boolean D = true;
  6. // Name for the SDP record when creating server socket
  7. private static final String NAME = "BluetoothChat";
  8. // Unique UUID for this application
  9. private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  10. // Member fields
  11. private final BluetoothAdapter mAdapter;
  12. private final Handler mHandler;
  13. private AcceptThread mAcceptThread;
  14. private ConnectThread mConnectThread;
  15. private ConnectedThread mConnectedThread;
  16. private int mState;
  17. // Constants that indicate the current connection state
  18. public static final int STATE_NONE = 0; // we're doing nothing
  19. public static final int STATE_LISTEN = 1; // now listening for incoming connections
  20. public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
  21. public static final int STATE_CONNECTED = 3; // now connected to a remote device
  22. /**
  23. * Constructor. Prepares a new BluetoothChat session.
  24. * @param context The UI Activity Context
  25. * @param handler A Handler to send messages back to the UI Activity
  26. */
  27. public BluetoothChatService(Context context,Handler handler) {
  28. mAdapter = BluetoothAdapter.getDefaultAdapter();
  29. mState = STATE_NONE;
  30. mHandler = handler;
  31. }
  32. /**
  33. * Set the current state of the chat connection
  34. * @param state An integer defining the current connection state
  35. */
  36. private synchronized void setState(int state) {
  37. if (D) Log.d(TAG,"setState() " + mState + " -> " + state);
  38. mState = state;
  39. // Give the new state to the Handler so the UI Activity can update
  40. mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE,state,-1).sendToTarget();
  41. }
  42. /**
  43. * Return the current connection state. */
  44. public synchronized int getState() {
  45. return mState;
  46. }
  47. /**
  48. * Start the chat service. Specifically start AcceptThread to begin a
  49. * session in listening (server) mode. Called by the Activity onResume() */
  50. public synchronized void start() {
  51. if (D) Log.d(TAG,"start");
  52. // Cancel any thread attempting to make a connection
  53. if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
  54. // Cancel any thread currently running a connection
  55. if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
  56. // Start the thread to listen on a BluetoothServerSocket
  57. if (mAcceptThread == null) {
  58. mAcceptThread = new AcceptThread();
  59. mAcceptThread.start();
  60. }
  61. setState(STATE_LISTEN);
  62. }
  63. /**
  64. * Start the ConnectThread to initiate a connection to a remote device.
  65. * @param device The BluetoothDevice to connect
  66. */
  67. public synchronized void connect(BluetoothDevice device) {
  68. if (D) Log.d(TAG,"connect to: " + device);
  69. // Cancel any thread attempting to make a connection
  70. if (mState == STATE_CONNECTING) {
  71. if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
  72. }
  73. // Cancel any thread currently running a connection
  74. if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
  75. // Start the thread to connect with the given device
  76. mConnectThread = new ConnectThread(device);
  77. mConnectThread.start();
  78. setState(STATE_CONNECTING);
  79. }
  80. /**
  81. * Start the ConnectedThread to begin managing a Bluetooth connection
  82. * @param socket The BluetoothSocket on which the connection was made
  83. * @param device The BluetoothDevice that has been connected
  84. */
  85. public synchronized void connected(BluetoothSocket socket,BluetoothDevice device) {
  86. if (D) Log.d(TAG,"connected");
  87. // Cancel the thread that completed the connection
  88. if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
  89. // Cancel any thread currently running a connection
  90. if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
  91. // Cancel the accept thread because we only want to connect to one device
  92. if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}
  93. // Start the thread to manage the connection and perform transmissions
  94. mConnectedThread = new ConnectedThread(socket);
  95. mConnectedThread.start();
  96. // Send the name of the connected device back to the UI Activity
  97. Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
  98. Bundle bundle = new Bundle();
  99. bundle.putString(BluetoothChat.DEVICE_NAME,device.getName());
  100. msg.setData(bundle);
  101. mHandler.sendMessage(msg);
  102. setState(STATE_CONNECTED);
  103. }
  104. /**
  105. * Stop all threads
  106. */
  107. public synchronized void stop() {
  108. if (D) Log.d(TAG,"stop");
  109. if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
  110. if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
  111. if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}
  112. setState(STATE_NONE);
  113. }
  114. /**
  115. * Write to the ConnectedThread in an unsynchronized manner
  116. * @param out The bytes to write
  117. * @see ConnectedThread#write(byte[])
  118. */
  119. public void write(byte[] out) {
  120. // Create temporary object
  121. ConnectedThread r;
  122. // Synchronize a copy of the ConnectedThread
  123. synchronized (this) {
  124. if (mState != STATE_CONNECTED) return;
  125. r = mConnectedThread;
  126. }
  127. // Perform the write unsynchronized
  128. r.write(out);
  129. }
  130. /**
  131. * Indicate that the connection attempt Failed and notify the UI Activity.
  132. */
  133. private void connectionFailed() {
  134. setState(STATE_LISTEN);
  135. // Send a failure message back to the Activity
  136. Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
  137. Bundle bundle = new Bundle();
  138. bundle.putString(BluetoothChat.TOAST,"Unable to connect device");
  139. msg.setData(bundle);
  140. mHandler.sendMessage(msg);
  141. }
  142. /**
  143. * Indicate that the connection was lost and notify the UI Activity.
  144. */
  145. private void connectionLost() {
  146. setState(STATE_LISTEN);
  147. // Send a failure message back to the Activity
  148. Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
  149. Bundle bundle = new Bundle();
  150. bundle.putString(BluetoothChat.TOAST,"Device connection was lost");
  151. msg.setData(bundle);
  152. mHandler.sendMessage(msg);
  153. }
  154. /**
  155. * This thread runs while listening for incoming connections. It behaves
  156. * like a server-side client. It runs until a connection is accepted
  157. * (or until cancelled).
  158. */
  159. private class AcceptThread extends Thread {
  160. // The local server socket
  161. private final BluetoothServerSocket mmServerSocket;
  162. public AcceptThread() {
  163. BluetoothServerSocket tmp = null;
  164. // Create a new listening server socket
  165. try {
  166. tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME,MY_UUID);
  167. } catch (IOException e) {
  168. Log.e(TAG,"listen() Failed",e);
  169. }
  170. mmServerSocket = tmp;
  171. }
  172. public void run() {
  173. if (D) Log.d(TAG,"BEGIN mAcceptThread" + this);
  174. setName("AcceptThread");
  175. BluetoothSocket socket = null;
  176. // Listen to the server socket if we're not connected
  177. while (mState != STATE_CONNECTED) {
  178. try {
  179. // This is a blocking call and will only return on a
  180. // successful connection or an exception
  181. socket = mmServerSocket.accept();
  182. } catch (IOException e) {
  183. Log.e(TAG,"accept() Failed",e);
  184. break;
  185. }
  186. // If a connection was accepted
  187. if (socket != null) {
  188. synchronized (BluetoothChatService.this) {
  189. switch (mState) {
  190. case STATE_LISTEN:
  191. case STATE_CONNECTING:
  192. // Situation normal. Start the connected thread.
  193. connected(socket,socket.getRemoteDevice());
  194. break;
  195. case STATE_NONE:
  196. case STATE_CONNECTED:
  197. // Either not ready or already connected. Terminate new socket.
  198. try {
  199. socket.close();
  200. } catch (IOException e) {
  201. Log.e(TAG,"Could not close unwanted socket",e);
  202. }
  203. break;
  204. }
  205. }
  206. }
  207. }
  208. if (D) Log.i(TAG,"END mAcceptThread");
  209. }
  210. public void cancel() {
  211. if (D) Log.d(TAG,"cancel " + this);
  212. try {
  213. mmServerSocket.close();
  214. } catch (IOException e) {
  215. Log.e(TAG,"close() of server Failed",e);
  216. }
  217. }
  218. }
  219. /**
  220. * This thread runs while attempting to make an outgoing connection
  221. * with a device. It runs straight through; the connection either
  222. * succeeds or fails.
  223. */
  224. private class ConnectThread extends Thread {
  225. private final BluetoothSocket mmSocket;
  226. private final BluetoothDevice mmDevice;
  227. public ConnectThread(BluetoothDevice device) {
  228. mmDevice = device;
  229. BluetoothSocket tmp = null;
  230. // Get a BluetoothSocket for a connection with the
  231. // given BluetoothDevice
  232. try {
  233. tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
  234. } catch (IOException e) {
  235. Log.e(TAG,"create() Failed",e);
  236. }
  237. mmSocket = tmp;
  238. }
  239. public void run() {
  240. Log.i(TAG,"BEGIN mConnectThread");
  241. setName("ConnectThread");
  242. // Always cancel discovery because it will slow down a connection
  243. mAdapter.cancelDiscovery();
  244. // Make a connection to the BluetoothSocket
  245. try {
  246. // This is a blocking call and will only return on a
  247. // successful connection or an exception
  248. mmSocket.connect();
  249. } catch (IOException e) {
  250. connectionFailed();
  251. // Close the socket
  252. try {
  253. mmSocket.close();
  254. } catch (IOException e2) {
  255. Log.e(TAG,"unable to close() socket during connection failure",e2);
  256. }
  257. // Start the service over to restart listening mode
  258. BluetoothChatService.this.start();
  259. return;
  260. }
  261. // Reset the ConnectThread because we're done
  262. synchronized (BluetoothChatService.this) {
  263. mConnectThread = null;
  264. }
  265. // Start the connected thread
  266. connected(mmSocket,mmDevice);
  267. }
  268. public void cancel() {
  269. try {
  270. mmSocket.close();
  271. } catch (IOException e) {
  272. Log.e(TAG,"close() of connect socket Failed",e);
  273. }
  274. }
  275. }
  276. /**
  277. * This thread runs during a connection with a remote device.
  278. * It handles all incoming and outgoing transmissions.
  279. */
  280. private class ConnectedThread extends Thread {
  281. private final BluetoothSocket mmSocket;
  282. private final InputStream mmInStream;
  283. private final OutputStream mmOutStream;
  284. public ConnectedThread(BluetoothSocket socket) {
  285. Log.d(TAG,"create ConnectedThread");
  286. mmSocket = socket;
  287. InputStream tmpIn = null;
  288. OutputStream tmpOut = null;
  289. // Get the BluetoothSocket input and output streams
  290. try {
  291. tmpIn = socket.getInputStream();
  292. tmpOut = socket.getOutputStream();
  293. } catch (IOException e) {
  294. Log.e(TAG,"temp sockets not created",e);
  295. }
  296. mmInStream = tmpIn;
  297. mmOutStream = tmpOut;
  298. }
  299. public void run() {
  300. Log.i(TAG,"BEGIN mConnectedThread");
  301. byte[] buffer = new byte[1024];
  302. int bytes;
  303. // Keep listening to the InputStream while connected
  304. while (true) {
  305. try {
  306. // Read from the InputStream
  307. bytes = mmInStream.read(buffer);
  308. // Send the obtained bytes to the UI Activity
  309. mHandler.obtainMessage(BluetoothChat.MESSAGE_READ,bytes,-1,buffer)
  310. .sendToTarget();
  311. } catch (IOException e) {
  312. Log.e(TAG,"disconnected",e);
  313. connectionLost();
  314. break;
  315. }
  316. }
  317. }
  318. /**
  319. * Write to the connected OutStream.
  320. * @param buffer The bytes to write
  321. */
  322. public void write(byte[] buffer) {
  323. try {
  324. mmOutStream.write(buffer);
  325. // Share the sent message back to the UI Activity
  326. mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE,buffer)
  327. .sendToTarget();
  328. } catch (IOException e) {
  329. Log.e(TAG,"Exception during write",e);
  330. }
  331. }
  332. public void cancel() {
  333. try {
  334. mmSocket.close();
  335. } catch (IOException e) {
  336. Log.e(TAG,e);
  337. }
  338. }
  339. }

}

设备列表活动代码在这里:

  1. package com.example.android.BluetoothChat;
  2. /**
  3. * This Activity appears as a dialog. It lists any paired devices and
  4. * devices detected in the area after discovery. When a device is chosen
  5. * by the user,the MAC address of the device is sent back to the parent
  6. * Activity in the result Intent.
  7. */
  8. public class DeviceListActivity extends Activity {
  9. // Debugging
  10. private static final String TAG = "DeviceListActivity";
  11. private static final boolean D = true;
  12. // Return Intent extra
  13. public static String EXTRA_DEVICE_ADDRESS = "device_address";
  14. // Member fields
  15. private BluetoothAdapter mBtAdapter;
  16. private ArrayAdapter

}

res文件夹可以原样复制.代码将起作用.

最佳答案
这就是答案!

我已经更换了这条线

  1. private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");

  1. private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

现在它工作!!!

非常感谢!

猜你在找的Android相关文章