这篇文章以代码为主,适合初学者。
这是一个两个android手机之间相连接的代码,中间有打开、关闭、discoverable设置、配对、链接监听、链接和链接后数据处理的实例。
初始化:
1.AndroidManifest.xml中的权限配置
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <permission android:name="android.permission.BLUETOOTH" android:label="BLUETOOTH" /> <permission android:name="android.permission.BLUETOOTH_ADMIN" /> <permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
UUID:
private static final UUID BTMODULEUUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
打开:
private void onClinkBluetoothOn(View view){ if(!mBTAdapter.isEnabled()){ mBTAdapter.enable(); Toast.makeText(this,"Opening Bluetooth", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this,"Bluetooth is already on!",Toast.LENGTH_SHORT).show(); } }
关闭:
private void onClinkBluetoothOff(View view){ if(mBTAdapter.isEnabled()){ mBTAdapter.disable(); Toast.makeText(this,"Turned off Bluetooth", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this,"Bluetooth is already off!",Toast.LENGTH_SHORT).show(); } }
可被发现,discoverable:
private void onClinkBluetoothDiscoverable(View view){ try { Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class); setDiscoverableTimeout.setAccessible(true); Method setScanMode = BluetoothAdapter.class.getMethod("setScanMode", int.class, int.class); setScanMode.setAccessible(true); setDiscoverableTimeout.invoke(mBTAdapter, 1); setScanMode.invoke(mBTAdapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE,1); ///mBTAdapter.get }catch (Exception e){ Toast.makeText(getBaseContext(), "Socket Creation failed!",Toast.LENGTH_SHORT).show(); } }
配对:
try { if(mBTAdapter.isDiscovering()) mBTAdapter.cancelDiscovery(); if(mBTDevice.getBondState() == BluetoothDevice.BOND_NONE){ Method createBond = BluetoothDevice.class.getMethod("createBond"); createBond.invoke(mBTDevice); } }catch (Exception e){ e.printStackTrace(); }
监听:
private class socketListenThread extends Thread { private final BluetoothServerSocket mmServerSocket; public socketListenThread(){ BluetoothServerSocket tmp = null; try { tmp = mBTAdapter.listenUsingRfcommWithServiceRecord(NAME_SERVER, BTMODULEUUID); }catch (Exception e){ e.printStackTrace(); } mmServerSocket = tmp; } public void run(){ BluetoothSocket socket = null; while(mState != STATE_CONNECTED){ try { socket = mmServerSocket.accept(); if(socket.isConnected()){ mConnectedThread = new connectedThread(socket); mConnectedThread.start(); break; } }catch (Exception e){ try { mmServerSocket.close(); }catch (Exception e1){ e1.printStackTrace(); } e.printStackTrace(); } } } public void cancel(){ try { mState = STATE_CONNECTED; if(mmServerSocket != null) mmServerSocket.close(); }catch (Exception e){ e.printStackTrace(); } } }
链接:
private AdapterView.OnItemClickListener mClickDeviceListListener = new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView> parent, View view, int position, long id) { if(!mBTAdapter.isEnabled()){ Toast.makeText(getBaseContext(),"Bluetooth not on", Toast.LENGTH_SHORT).show(); } String info = ((TextView) view).getText().toString(); final String address = info.substring(info.length()-17); final String name = info.substring(0,info.length()-17); mBTDevice = mBTAdapter.getRemoteDevice(address); try { if(mBTAdapter.isDiscovering()) mBTAdapter.cancelDiscovery(); if(mBTDevice.getBondState() == BluetoothDevice.BOND_NONE){ Method createBond = BluetoothDevice.class.getMethod("createBond"); createBond.invoke(mBTDevice); } }catch (Exception e){ e.printStackTrace(); } //create a new thread to avoid blocking the GUI new Thread() { public void run(){ ///BluetoothDevice device = mBTAdapter.getRemoteDevice(address); try { if(mBTAdapter.isDiscovering()) mBTAdapter.cancelDiscovery(); mBTSocket = mBTDevice.createRfcommSocketToServiceRecord(BTMODULEUUID); //mBTSocket = createB }catch (Exception e){ Toast.makeText(getBaseContext(), "Socket Creation failed!",Toast.LENGTH_SHORT).show(); } try{ mBTSocket.connect(); mConnectedThread = new connectedThread(mBTSocket); mConnectedThread.start(); }catch (Exception e){ try { mBTSocket.close(); }catch (Exception e2){ Toast.makeText(getBaseContext(),"Socket Creation failed", Toast.LENGTH_SHORT).show(); } } } }.start(); } };
数据传输:
private class connectedThread extends Thread{ private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public connectedThread(BluetoothSocket socket){ InputStream mmIn = null; OutputStream mmOut = null; mmSocket = socket; try { mmIn = socket.getInputStream(); mmOut = socket.getOutputStream(); }catch (Exception e){ e.printStackTrace(); } mState = STATE_CONNECTED; mmInStream = mmIn; mmOutStream = mmOut; } public void run(){ byte[] readBuffer = new byte[1024]; int bytes; while(mmSocket.isConnected()){ try { Thread.sleep(20); bytes = mmInStream.read(readBuffer); mHandlerMessage.obtainMessage(InterfaceCommon.MESSAGE_READ_SOCKET, bytes, -1, readBuffer).sendToTarget(); }catch (Exception e){ e.printStackTrace(); } } }///run() public void write(byte[] buffer){ try { mmOutStream.write(buffer); mHandlerMessage.obtainMessage(InterfaceCommon.MESSAGE_WRITE_SOCKET, buffer.length, -1, buffer).sendToTarget(); }catch (Exception e){ e.printStackTrace(); } } public void cancel(){ try { mmSocket.close(); }catch (Exception e){ e.printStackTrace(); } } }///connectedThread