蓝牙通信的大概过程例如以下:

1。首先开启蓝牙

2,搜索可用设备

3,创建蓝牙socket。获取输入输出流

4,读取和写入数据

5。断开连接关闭蓝牙

还要发送配对码发送进行推断!

以下是全部的源码;不会非常难;认真看;

SearchDeviceActivity.java

[java] view
plain
copy

  1. package com.hello.project;
  2. import java.util.ArrayList;
  3. import java.util.Iterator;
  4. import java.util.List;
  5. import java.util.Set;
  6. import android.app.Activity;
  7. import android.app.AlertDialog;
  8. import android.bluetooth.BluetoothAdapter;
  9. import android.bluetooth.BluetoothDevice;
  10. import android.content.BroadcastReceiver;
  11. import android.content.Context;
  12. import android.content.DialogInterface;
  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.view.View.OnClickListener;
  19. import android.widget.AdapterView;
  20. import android.widget.AdapterView.OnItemClickListener;
  21. import android.widget.ArrayAdapter;
  22. import android.widget.Button;
  23. import android.widget.ListView;
  24. public class SearchDeviceActivity extends Activity implements OnItemClickListener{
  25. private BluetoothAdapter blueadapter=null;
  26. private DeviceReceiver mydevice=new DeviceReceiver();
  27. private List<String> deviceList=new ArrayList<String>();
  28. private ListView deviceListview;
  29. private Button btserch;
  30. private ArrayAdapter<String> adapter;
  31. private boolean hasregister=false;
  32. @Override
  33. protected void onCreate(Bundle savedInstanceState) {
  34. super.onCreate(savedInstanceState);
  35. setContentView(R.layout.finddevice);
  36. setView();
  37. setBluetooth();
  38. }
  39. private void setView(){
  40. deviceListview=(ListView)findViewById(R.id.devicelist);
  41. adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, deviceList);
  42. deviceListview.setAdapter(adapter);
  43. deviceListview.setOnItemClickListener(this);
  44. btserch=(Button)findViewById(R.id.start_seach);
  45. btserch.setOnClickListener(new ClinckMonitor());
  46. }
  47. @Override
  48. protected void onStart() {
  49. //注冊蓝牙接收广播
  50. if(!hasregister){
  51. hasregister=true;
  52. IntentFilter filterStart=new IntentFilter(BluetoothDevice.ACTION_FOUND);
  53. IntentFilter filterEnd=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
  54. registerReceiver(mydevice, filterStart);
  55. registerReceiver(mydevice, filterEnd);
  56. }
  57. super.onStart();
  58. }
  59. @Override
  60. protected void onDestroy() {
  61. if(blueadapter!=null&&blueadapter.isDiscovering()){
  62. blueadapter.cancelDiscovery();
  63. }
  64. if(hasregister){
  65. hasregister=false;
  66. unregisterReceiver(mydevice);
  67. }
  68. super.onDestroy();
  69. }
  70. /**
  71. * Setting Up Bluetooth
  72. */
  73. private void setBluetooth(){
  74. blueadapter=BluetoothAdapter.getDefaultAdapter();
  75. if(blueadapter!=null){  //Device support Bluetooth
  76. //确认开启蓝牙
  77. if(!blueadapter.isEnabled()){
  78. //请求用户开启
  79. Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  80. startActivityForResult(intent, RESULT_FIRST_USER);
  81. //使蓝牙设备可见,方便配对
  82. Intent in=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  83. in.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 200);
  84. startActivity(in);
  85. //直接开启,不经过提示
  86. blueadapter.enable();
  87. }
  88. }
  89. else{   //Device does not support Bluetooth
  90. AlertDialog.Builder dialog = new AlertDialog.Builder(this);
  91. dialog.setTitle("No bluetooth devices");
  92. dialog.setMessage("Your equipment does not support bluetooth, please change device");
  93. dialog.setNegativeButton("cancel",
  94. new DialogInterface.OnClickListener() {
  95. @Override
  96. public void onClick(DialogInterface dialog, int which) {
  97. }
  98. });
  99. dialog.show();
  100. }
  101. }
  102. /**
  103. * Finding Devices
  104. */
  105. private void findAvalibleDevice(){
  106. //获取可配对蓝牙设备
  107. Set<BluetoothDevice> device=blueadapter.getBondedDevices();
  108. if(blueadapter!=null&&blueadapter.isDiscovering()){
  109. deviceList.clear();
  110. adapter.notifyDataSetChanged();
  111. }
  112. if(device.size()>0){ //存在已经配对过的蓝牙设备
  113. for(Iterator<BluetoothDevice> it=device.iterator();it.hasNext();){
  114. BluetoothDevice btd=it.next();
  115. deviceList.add(btd.getName()+'\n'+btd.getAddress());
  116. adapter.notifyDataSetChanged();
  117. }
  118. }else{  //不存在已经配对过的蓝牙设备
  119. deviceList.add("No can be matched to use bluetooth");
  120. adapter.notifyDataSetChanged();
  121. }
  122. }
  123. @Override
  124. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  125. switch(resultCode){
  126. case RESULT_OK:
  127. findAvalibleDevice();
  128. break;
  129. case RESULT_CANCELED:
  130. break;
  131. }
  132. super.onActivityResult(requestCode, resultCode, data);
  133. }
  134. private class ClinckMonitor implements OnClickListener{
  135. @Override
  136. public void onClick(View v) {
  137. if(blueadapter.isDiscovering()){
  138. blueadapter.cancelDiscovery();
  139. btserch.setText("repeat search");
  140. }else{
  141. findAvalibleDevice();
  142. blueadapter.startDiscovery();
  143. btserch.setText("stop search");
  144. }
  145. }
  146. }
  147. /**
  148. * 蓝牙搜索状态广播监听
  149. * @author Andy
  150. *
  151. */
  152. private class DeviceReceiver extends BroadcastReceiver{
  153. @Override
  154. public void onReceive(Context context, Intent intent) {
  155. String action =intent.getAction();
  156. if(BluetoothDevice.ACTION_FOUND.equals(action)){    //搜索到新设备
  157. BluetoothDevice btd=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  158. //搜索没有配过对的蓝牙设备
  159. if (btd.getBondState() != BluetoothDevice.BOND_BONDED) {
  160. deviceList.add(btd.getName()+'\n'+btd.getAddress());
  161. adapter.notifyDataSetChanged();
  162. }
  163. }
  164. else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){   //搜索结束
  165. if (deviceListview.getCount() == 0) {
  166. deviceList.add("No can be matched to use bluetooth");
  167. adapter.notifyDataSetChanged();
  168. }
  169. btserch.setText("repeat search");
  170. }
  171. }
  172. }
  173. @Override
  174. public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
  175. Log.e("msgParent", "Parent= "+arg0);
  176. Log.e("msgView", "View= "+arg1);
  177. Log.e("msgChildView", "ChildView= "+arg0.getChildAt(pos-arg0.getFirstVisiblePosition()));
  178. final String msg = deviceList.get(pos);
  179. if(blueadapter!=null&&blueadapter.isDiscovering()){
  180. blueadapter.cancelDiscovery();
  181. btserch.setText("repeat search");
  182. }
  183. AlertDialog.Builder dialog = new AlertDialog.Builder(this);// 定义一个弹出框对象
  184. dialog.setTitle("Confirmed connecting device");
  185. dialog.setMessage(msg);
  186. dialog.setPositiveButton("connect",
  187. new DialogInterface.OnClickListener() {
  188. @Override
  189. public void onClick(DialogInterface dialog, int which) {
  190. BluetoothMsg.BlueToothAddress=msg.substring(msg.length()-17);
  191. if(BluetoothMsg.lastblueToothAddress!=BluetoothMsg.BlueToothAddress){
  192. BluetoothMsg.lastblueToothAddress=BluetoothMsg.BlueToothAddress;
  193. }
  194. Intent in=new Intent(SearchDeviceActivity.this,BluetoothActivity.class);
  195. startActivity(in);
  196. }
  197. });
  198. dialog.setNegativeButton("cancel",
  199. new DialogInterface.OnClickListener() {
  200. @Override
  201. public void onClick(DialogInterface dialog, int which) {
  202. BluetoothMsg.BlueToothAddress = null;
  203. }
  204. });
  205. dialog.show();
  206. }
  207. }

BluetoothMsg.java

[java] view
plain
copy

  1. package com.hello.project;
  2. public class BluetoothMsg {
  3. /**
  4. * 蓝牙连接类型
  5. * @author Andy
  6. *
  7. */
  8. public enum ServerOrCilent{
  9. NONE,
  10. SERVICE,
  11. CILENT
  12. };
  13. //蓝牙连接方式
  14. public static ServerOrCilent serviceOrCilent = ServerOrCilent.NONE;
  15. //连接蓝牙地址
  16. public static String BlueToothAddress = null,lastblueToothAddress=null;
  17. //通信线程是否开启
  18. public static boolean isOpen = false;
  19. }

finddevice.xml

[java] view
plain
copy

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:id = "@+id/devices"
  4. android:orientation="vertical"
  5. android:layout_width="fill_parent"
  6. android:layout_height="fill_parent"
  7. >
  8. <RelativeLayout
  9. android:layout_width="fill_parent"
  10. android:layout_height="wrap_content"
  11. android:layout_alignParentBottom = "true"
  12. android:id= "@+id/bt_bottombar">
  13. <Button android:id="@+id/start_seach"
  14. android:layout_width="match_parent"
  15. android:layout_height="wrap_content"
  16. android:layout_toRightOf="@+id/start_service"
  17. android:text="Began to search"/>
  18. </RelativeLayout>
  19. <ListView
  20. android:id="@+id/devicelist"
  21. android:layout_width="fill_parent"
  22. android:layout_height="fill_parent"
  23. android:scrollingCache="false"
  24. android:divider="#ffc6c6c6"
  25. android:layout_weight="1.0"
  26. android:layout_above = "@id/bt_bottombar"
  27. android:layout_below="@id/devices"
  28. />
  29. </RelativeLayout>

BluetoothActivity.java

[java] view
plain
copy

  1. package com.hello.project;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.OutputStream;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import java.util.UUID;
  8. import android.app.Activity;
  9. import android.bluetooth.BluetoothAdapter;
  10. import android.bluetooth.BluetoothDevice;
  11. import android.bluetooth.BluetoothServerSocket;
  12. import android.bluetooth.BluetoothSocket;
  13. import android.content.Context;
  14. import android.os.Bundle;
  15. import android.os.Handler;
  16. import android.os.Message;
  17. import android.util.Log;
  18. import android.view.View;
  19. import android.view.View.OnClickListener;
  20. import android.view.inputmethod.InputMethodManager;
  21. import android.widget.AdapterView;
  22. import android.widget.ArrayAdapter;
  23. import android.widget.Button;
  24. import android.widget.EditText;
  25. import android.widget.ListView;
  26. import android.widget.Toast;
  27. import android.widget.AdapterView.OnItemClickListener;
  28. public class BluetoothActivity extends  Activity{
  29. /* 一些常量。代表server的名称 */
  30. public static final String PROTOCOL_SCHEME_RFCOMM = "btspp";
  31. private ListView mListView;
  32. private Button sendButton;
  33. private Button disconnectButton;
  34. private EditText editMsgView;
  35. private ArrayAdapter<String> mAdapter;
  36. private List<String> msgList=new ArrayList<String>();
  37. Context mContext;
  38. private BluetoothServerSocket mserverSocket = null;
  39. private ServerThread startServerThread = null;
  40. private clientThread clientConnectThread = null;
  41. private BluetoothSocket socket = null;
  42. private BluetoothDevice device = null;
  43. private readThread mreadThread = null;;
  44. private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  45. @Override
  46. public void onCreate(Bundle savedInstanceState) {
  47. super.onCreate(savedInstanceState);
  48. setContentView(R.layout.chat);
  49. mContext = this;
  50. init();
  51. }
  52. private void init() {
  53. mAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, msgList);
  54. mListView = (ListView) findViewById(R.id.list);
  55. mListView.setAdapter(mAdapter);
  56. mListView.setFastScrollEnabled(true);
  57. editMsgView= (EditText)findViewById(R.id.MessageText);
  58. editMsgView.clearFocus();
  59. sendButton= (Button)findViewById(R.id.btn_msg_send);
  60. sendButton.setOnClickListener(new OnClickListener() {
  61. @Override
  62. public void onClick(View arg0) {
  63. String msgText =editMsgView.getText().toString();
  64. if (msgText.length()>0) {
  65. sendMessageHandle(msgText);
  66. editMsgView.setText("");
  67. editMsgView.clearFocus();
  68. //close InputMethodManager
  69. InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
  70. imm.hideSoftInputFromWindow(editMsgView.getWindowToken(), 0);
  71. }else
  72. Toast.makeText(mContext, "发送内容不能为空!", Toast.LENGTH_SHORT).show();
  73. }
  74. });
  75. disconnectButton= (Button)findViewById(R.id.btn_disconnect);
  76. disconnectButton.setOnClickListener(new OnClickListener() {
  77. @Override
  78. public void onClick(View arg0) {
  79. // TODO Auto-generated method stub
  80. if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.CILENT)
  81. {
  82. shutdownClient();
  83. }
  84. else if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.SERVICE)
  85. {
  86. shutdownServer();
  87. }
  88. BluetoothMsg.isOpen = false;
  89. BluetoothMsg.serviceOrCilent=BluetoothMsg.ServerOrCilent.NONE;
  90. Toast.makeText(mContext, "已断开连接。", Toast.LENGTH_SHORT).show();
  91. }
  92. });
  93. }
  94. private Handler LinkDetectedHandler = new Handler() {
  95. @Override
  96. public void handleMessage(Message msg) {
  97. //Toast.makeText(mContext, (String)msg.obj, Toast.LENGTH_SHORT).show();
  98. if(msg.what==1)
  99. {
  100. msgList.add((String)msg.obj);
  101. }
  102. else
  103. {
  104. msgList.add((String)msg.obj);
  105. }
  106. mAdapter.notifyDataSetChanged();
  107. mListView.setSelection(msgList.size() - 1);
  108. }
  109. };
  110. @Override
  111. protected void onResume() {
  112. BluetoothMsg.serviceOrCilent=BluetoothMsg.ServerOrCilent.CILENT;
  113. if(BluetoothMsg.isOpen)
  114. {
  115. Toast.makeText(mContext, "连接已经打开。能够通信。假设要再建立连接,请先断开!

    ", Toast.LENGTH_SHORT).show();

  116. return;
  117. }
  118. if(BluetoothMsg.serviceOrCilent==BluetoothMsg.ServerOrCilent.CILENT)
  119. {
  120. String address = BluetoothMsg.BlueToothAddress;
  121. if(!address.equals("null"))
  122. {
  123. device = mBluetoothAdapter.getRemoteDevice(address);
  124. clientConnectThread = new clientThread();
  125. clientConnectThread.start();
  126. BluetoothMsg.isOpen = true;
  127. }
  128. else
  129. {
  130. Toast.makeText(mContext, "address is null !", Toast.LENGTH_SHORT).show();
  131. }
  132. }
  133. else if(BluetoothMsg.serviceOrCilent==BluetoothMsg.ServerOrCilent.SERVICE)
  134. {
  135. startServerThread = new ServerThread();
  136. startServerThread.start();
  137. BluetoothMsg.isOpen = true;
  138. }
  139. super.onResume();
  140. }
  141. //开启client
  142. private class clientThread extends Thread {
  143. @Override
  144. public void run() {
  145. try {
  146. //创建一个Socket连接:仅仅须要server在注冊时的UUID号
  147. // socket = device.createRfcommSocketToServiceRecord(BluetoothProtocols.OBEX_OBJECT_PUSH_PROTOCOL_UUID);
  148. socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
  149. //连接
  150. Message msg2 = new Message();
  151. msg2.obj = "请稍候。正在连接server:"+BluetoothMsg.BlueToothAddress;
  152. msg2.what = 0;
  153. LinkDetectedHandler.sendMessage(msg2);
  154. socket.connect();
  155. Message msg = new Message();
  156. msg.obj = "已经连接上服务端。能够发送信息。";
  157. msg.what = 0;
  158. LinkDetectedHandler.sendMessage(msg);
  159. //启动接受数据
  160. mreadThread = new readThread();
  161. mreadThread.start();
  162. }
  163. catch (IOException e)
  164. {
  165. Log.e("connect", "", e);
  166. Message msg = new Message();
  167. msg.obj = "连接服务端异常!断开连接又一次试一试。";
  168. msg.what = 0;
  169. LinkDetectedHandler.sendMessage(msg);
  170. }
  171. }
  172. };
  173. //开启server
  174. private class ServerThread extends Thread {
  175. @Override
  176. public void run() {
  177. try {
  178. /* 创建一个蓝牙server
  179. * 參数分别:server名称、UUID   */
  180. mserverSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM,
  181. UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
  182. Log.d("server", "wait cilent connect...");
  183. Message msg = new Message();
  184. msg.obj = "请稍候。正在等待client的连接...";
  185. msg.what = 0;
  186. LinkDetectedHandler.sendMessage(msg);
  187. /* 接受client的连接请求 */
  188. socket = mserverSocket.accept();
  189. Log.d("server", "accept success !");
  190. Message msg2 = new Message();
  191. String info = "client已经连接上!能够发送信息。";
  192. msg2.obj = info;
  193. msg.what = 0;
  194. LinkDetectedHandler.sendMessage(msg2);
  195. //启动接受数据
  196. mreadThread = new readThread();
  197. mreadThread.start();
  198. } catch (IOException e) {
  199. e.printStackTrace();
  200. }
  201. }
  202. };
  203. /* 停止server */
  204. private void shutdownServer() {
  205. new Thread() {
  206. @Override
  207. public void run() {
  208. if(startServerThread != null)
  209. {
  210. startServerThread.interrupt();
  211. startServerThread = null;
  212. }
  213. if(mreadThread != null)
  214. {
  215. mreadThread.interrupt();
  216. mreadThread = null;
  217. }
  218. try {
  219. if(socket != null)
  220. {
  221. socket.close();
  222. socket = null;
  223. }
  224. if (mserverSocket != null)
  225. {
  226. mserverSocket.close();/* 关闭服务器 */
  227. mserverSocket = null;
  228. }
  229. } catch (IOException e) {
  230. Log.e("server", "mserverSocket.close()", e);
  231. }
  232. };
  233. }.start();
  234. }
  235. /* 停止client连接 */
  236. private void shutdownClient() {
  237. new Thread() {
  238. @Override
  239. public void run() {
  240. if(clientConnectThread!=null)
  241. {
  242. clientConnectThread.interrupt();
  243. clientConnectThread= null;
  244. }
  245. if(mreadThread != null)
  246. {
  247. mreadThread.interrupt();
  248. mreadThread = null;
  249. }
  250. if (socket != null) {
  251. try {
  252. socket.close();
  253. } catch (IOException e) {
  254. // TODO Auto-generated catch block
  255. e.printStackTrace();
  256. }
  257. socket = null;
  258. }
  259. };
  260. }.start();
  261. }
  262. //发送数据
  263. private void sendMessageHandle(String msg)
  264. {
  265. if (socket == null)
  266. {
  267. Toast.makeText(mContext, "没有连接", Toast.LENGTH_SHORT).show();
  268. return;
  269. }
  270. try {
  271. OutputStream os = socket.getOutputStream();
  272. os.write(msg.getBytes());
  273. } catch (IOException e) {
  274. e.printStackTrace();
  275. }
  276. msgList.add(msg);
  277. mAdapter.notifyDataSetChanged();
  278. mListView.setSelection(msgList.size() - 1);
  279. }
  280. //读取数据
  281. private class readThread extends Thread {
  282. @Override
  283. public void run() {
  284. byte[] buffer = new byte[1024];
  285. int bytes;
  286. InputStream mmInStream = null;
  287. try {
  288. mmInStream = socket.getInputStream();
  289. } catch (IOException e1) {
  290. // TODO Auto-generated catch block
  291. e1.printStackTrace();
  292. }
  293. while (true) {
  294. try {
  295. // Read from the InputStream
  296. if( (bytes = mmInStream.read(buffer)) > 0 )
  297. {
  298. byte[] buf_data = new byte[bytes];
  299. for(int i=0; i<bytes; i++)
  300. {
  301. buf_data[i] = buffer[i];
  302. }
  303. String s = new String(buf_data);
  304. Message msg = new Message();
  305. msg.obj = s;
  306. msg.what = 1;
  307. LinkDetectedHandler.sendMessage(msg);
  308. }
  309. } catch (IOException e) {
  310. try {
  311. mmInStream.close();
  312. } catch (IOException e1) {
  313. // TODO Auto-generated catch block
  314. e1.printStackTrace();
  315. }
  316. break;
  317. }
  318. }
  319. }
  320. }
  321. @Override
  322. protected void onDestroy() {
  323. super.onDestroy();
  324. if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.CILENT)
  325. {
  326. shutdownClient();
  327. }
  328. else if (BluetoothMsg.serviceOrCilent == BluetoothMsg.ServerOrCilent.SERVICE)
  329. {
  330. shutdownServer();
  331. }
  332. BluetoothMsg.isOpen = false;
  333. BluetoothMsg.serviceOrCilent = BluetoothMsg.ServerOrCilent.NONE;
  334. }
  335. }

chat.xml

[java] view
plain
copy

  1. <?xml version="1.0" encoding="utf-8"?

    >

  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:id = "@+id/container"
  4. android:orientation="vertical"
  5. android:layout_width="fill_parent"
  6. android:layout_height="fill_parent"
  7. >
  8. <RelativeLayout
  9. android:layout_width="fill_parent"
  10. android:layout_height="wrap_content"
  11. android:id= "@+id/edit_bottombar"
  12. android:layout_alignParentBottom = "true">
  13. <Button android:id="@+id/btn_disconnect"
  14. android:layout_width="65dp"
  15. android:layout_height="wrap_content"
  16. android:layout_alignParentLeft ="true"
  17. android:text="断开"/>
  18. <Button android:id="@+id/btn_msg_send"
  19. android:layout_width="65dp"
  20. android:layout_height="wrap_content"
  21. android:layout_alignParentRight ="true"
  22. android:text="发送"/>
  23. <EditText
  24. android:layout_width="fill_parent"
  25. android:layout_height = "wrap_content"
  26. android:layout_toLeftOf="@id/btn_msg_send"
  27. android:layout_toRightOf="@+id/btn_disconnect"
  28. android:hint = "说点什么呢?"
  29. android:textSize="15dip"
  30. android:id = "@+id/MessageText"/>
  31. </RelativeLayout>
  32. <ListView
  33. android:id="@+id/list"
  34. android:layout_width="fill_parent"
  35. android:layout_height="fill_parent"
  36. android:scrollingCache="false"
  37. android:divider="#ffc6c6c6"
  38. android:layout_weight="1.0"
  39. android:layout_above = "@id/edit_bottombar"
  40. android:layout_below="@id/container"
  41. />
  42. </RelativeLayout>

最后别忘了增加权限

[java] view
plain
copy

  1. <uses-permission android:name="android.permission.BLUETOOTH"/>
  2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
  3. <uses-permission android:name="android.permission.READ_CONTACTS"/>

扩展:蓝牙后台配对实现(网上看到的整理例如以下)

[java] view
plain
copy

  1. static public boolean createBond(Class btClass, BluetoothDevice btDevice)
  2. throws Exception {
  3. Method createBondMethod = btClass.getMethod("createBond");
  4. Log.i("life", "createBondMethod = " + createBondMethod.getName());
  5. Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
  6. return returnValue.booleanValue();
  7. }
  8. static public boolean setPin(Class btClass, BluetoothDevice btDevice,
  9. String str) throws Exception {
  10. Boolean returnValue = null;
  11. try {
  12. Method removeBondMethod = btClass.getDeclaredMethod("setPin",
  13. new Class[] { byte[].class });
  14. returnValue = (Boolean) removeBondMethod.invoke(btDevice,
  15. new Object[] { str.getBytes() });
  16. Log.i("life", "returnValue = " + returnValue);
  17. } catch (SecurityException e) {
  18. // throw new RuntimeException(e.getMessage());
  19. e.printStackTrace();
  20. } catch (IllegalArgumentException e) {
  21. // throw new RuntimeException(e.getMessage());
  22. e.printStackTrace();
  23. } catch (Exception e) {
  24. // TODO Auto-generated catch block
  25. e.printStackTrace();
  26. }
  27. return returnValue;
  28. }
  29. // 取消用户输入
  30. static public boolean cancelPairingUserInput(Class btClass,
  31. BluetoothDevice device) throws Exception {
  32. Method createBondMethod = btClass.getMethod("cancelPairingUserInput");
  33. // cancelBondProcess()
  34. Boolean returnValue = (Boolean) createBondMethod.invoke(device);
  35. Log.i("life", "cancelPairingUserInputreturnValue = " + returnValue);
  36. return returnValue.booleanValue();
  37. }

然后监听蓝牙配对的广播  匹配“android.bluetooth.device.action.PAIRING_REQUEST”这个action

然后调用上面的setPin(mDevice.getClass(), mDevice, "1234"); // 手机和蓝牙採集器配对

createBond(mDevice.getClass(), mDevice);

cancelPairingUserInput(mDevice.getClass(), mDevice);

mDevice是你要去连接的那个蓝牙的对象 , 1234为配对的pin码


Android蓝牙通信具体解释的更多相关文章

  1. Android蓝牙通信总结

    这篇文章要达到的目标: 1.介绍在Android系统上实现蓝牙通信的过程中涉及到的概念. 2.在android系统上实现蓝牙通信的步骤. 3.在代码实现上的考虑. 4.例子代码实现(手持设备和蓝牙串口 ...

  2. Qt on Android 蓝牙通信开发

    版权声明:本文为MULTIBEANS ORG研发跟随文章,未经MLT ORG允许不得转载. 最近做项目,需要开发安卓应用,实现串口的收发,目测CH340G在安卓手机上非常麻烦,而且驱动都是Java版本 ...

  3. Android蓝牙通信

    Android为蓝牙设备之间的通信封装好了一些调用接口,使得实现Android的蓝牙通信功能并不困难.可通过UUID使两个设备直接建立连接. 具体步骤: 1. 获取BluetoothAdapter实例 ...

  4. android蓝牙协议名词解释 OPP HFP HDP A2DP PAN

    各种蓝牙协议的全称: OPP:对象存储规范(Object Push Profile),最为常见的,文件的传输都是使用此协议. HFP:(Hands-free Profile),让蓝牙设备能够控制电话, ...

  5. (转)android 蓝牙通信编程

    转自:http://blog.csdn.net/pwei007/article/details/6015907 Android平台支持蓝牙网络协议栈,实现蓝牙设备之间数据的无线传输. 本文档描述了怎样 ...

  6. Android蓝牙通信功能开发

    1. 概述 Bluetooth 是几乎现在每部手机标准配备的功能,多用于耳机 mic 等设备与手机的连接,除此之外,还可以多部手机之间建立 bluetooth 通信,本文就通过 SDK 中带的一个聊天 ...

  7. android 蓝牙通信编程讲解

    以下是开发中的几个关键步骤: 1,首先开启蓝牙 2,搜索可用设备 3,创建蓝牙socket,获取输入输出流 4,读取和写入数据 5,断开连接关闭蓝牙 下面是一个demo 效果图: SearchDevi ...

  8. android 蓝牙 通信 bluetooth

    此例子基于 android demo Android的蓝牙开发,虽然不多用,但有时还是会用到,  Android对于蓝牙开发从2.0版本的sdk才开始支持,而且模拟器不支持,测试需要两部手机:     ...

  9. Android 蓝牙通信——AndroidBluetoothManager

    转载请说明出处! 作者:kqw攻城狮 出处:个人站 | CSDN To get a Git project into your build: Step 1. Add the JitPack repos ...

随机推荐

  1. App Distribution Guide (一)

    This guide contains everything you need to know to distribute an app through the App Store or Mac Ap ...

  2. kubernetes1.5.2--部署DNS服务

    本文基于kubernetes 1.5.2版本编写 在kubernetes1.2之前,采用skydns+kube2dns+etcd的方式来部署dns.而从1.3开始,则部署方式有了一点儿变化,将skyd ...

  3. python virtualenv virtualenvwrapper

    python中的virtualenv模块能够将项目环境分隔开,而不是使用全局的环境,非常实用. 首先pip install virtualenv 如何创建一个环境virtualenv testvir ...

  4. PS 如何制作环绕文字效果

    最终效果 地球素材 1.打开素材,使用椭圆选区工具按住shift绘制正圆选区 2.转到路径面板,将选区变为工作路径 3.选择文字工具,在路径上输入文字 4.ctrl+T,按住ctrl+alt,鼠标拖动 ...

  5. Splay树(多操作)——POJ 3580 SuperMemo

    相应POJ题目:点击打开链接 SuperMemo Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 11309   Accept ...

  6. SVN遇到Can't convert string from 'UTF-8' to native encoding(转)

    svn: Can't convert string from 'UTF-8' to native encoding: svn: platform/console-framework/portal/im ...

  7. HTML5实战与剖析之媒体元素(6、视频实例)

    HTML5中的视频标签和及其模仿视频播放器的效果在一些手机端应用比較多.由于手机端基本上废除了flash的独断.让HTML5当家做主人,所以对视频支持的比較好. 所以今天专门为大家奉上HTML5视频标 ...

  8. 关于TCP/IP,这十个问题你都知道,就入门了!

    关于TCP/IP,必知必会的十个问题 本文整理了一些TCP/IP协议簇中需要必知必会的十大问题,既是面试高频问题,又是程序员必备基础素养.   TCP/IP十个问题 一.TCP/IP模型 TCP/IP ...

  9. Spark中经常使用工具类Utils的简明介绍

    <深入理解Spark:核心思想与源代码分析>一书前言的内容请看链接<深入理解SPARK:核心思想与源代码分析>一书正式出版上市 <深入理解Spark:核心思想与源代码分析 ...

  10. MongoDB 的聚集操作

    聚合引言 聚集操作就是出来数据记录并返回计算结果的操作.MongoDB提供了丰富的聚集操作.可以检測和执行数据集上的计算.执行在mongod上的数据聚集简化了代码和资源限制. 像查询一样,在Mongo ...