Android项目中Bluetooth类如何写
Android項目開發中的藍牙類的編寫,總結一下
藍牙相關類的總結:
1.BluetoothSocket 類的定義格式如下:
public static class Gallery.LayoutParams extends ViewGroup.LayoutParams累BluetoothSocket的定義結構如下: java.lang.Object android.view.ViewGroup.LayoutParams android.widget.Gallery.LayoutParamsAndroid的藍牙系統與Socket套接字密切相關,藍牙端的監聽接口和TCP的端口類似,均使用了Socket和ServerSocket類。在服務器端,使用BlueServerSocket類來創建一個監聽服務器端口,當一個連接被BluetoothServerSocket所接受,會返回一個新的BluetoothSocket來管理該連接,在客戶端,使用一個單獨的BlueSocket類去初始化一個外界連接和管理該連接。為了創建一個Bluetooth去連接到一個已知設備,使用方法BluetoothDevice。createRfcommSocketToServiceRecord()。然后調用connect()方法去嘗試一個面向遠程設備的連接,這個調用將被阻塞,直到一個連接已經建立或者該連接失效。
為了創建一個BluetoothSocket作為服務器,每當該端口連接成功后,無論它初始化為客戶端,或者被接收為服務端,都是通過方法getInputStream()和getOutputStream()來打開I/O流,從而獲得各自的InputStream和OutputStream對象
2.BluetoothServerSocket類的格式如下:
public final class BluetoothServerSocket extends Object implements Closeable類BluetoothServerSocket的結構如下:java.lang.Object
android.bluetooth.BluetoothServerSocket3.BluetoothAdapter類的格式如下: public final class BluetoothAdapter extends Object 類BluetoothAdapter結構如下: java.lang.Object android.bluetooth.BluetoothAdapterBluetoothAdapter代表本地的藍牙配適器設備,通過此類可以讓用戶執行基本的藍牙任務,例如,初始化設備的搜索,查詢可匹配的設備集,使用一個已知的MAC地址來初始化一個BluetoothDevice類,創建一個BluetoothServerSocket類似監聽其他設備對本機的連接請求等。為了得到這個代表本地藍牙配適器的BluetoothAdapter類,需要調用靜態方法getDefaultAdapter(),這是所有藍牙動作的第一步,當擁有本地配適器之后,用戶可以獲得一系列的BluetoothDevice對象,這些對象代表所有擁有getBondedDevice()方法的已經匹配的設備,用startDiscovery()方法來開始設備的搜尋,或者創建一個BluetoothServerSocket類,通過listenUsingRfcommWithServiceRecord(String, UUID)方法來監聽新來的連接請求。
注:大部分需要BLUETOOTH權限,一些方法同時需要BLUETOOTH——ADMIN權限
首先,該導的包,該聲明的常量,變量,對象等,如下
開始構建管理共享的方法:
接下來就是處理已連接的線程:
public ConnectedThread(BluetoothSocket socket){mmSocket = socket;mRx = new ArrayList<Byte>();InputStream tmpIn = null;OutputStream tmpOut = null;try {tmpIn = socket.getInputStream();tmpOut = socket.getOutputStream();} catch (IOException e) {e.printStackTrace();}mmInStream = tmpIn;mmOutStream = tmpOut;}public void run(){byte[] buffer = new byte[1024];int bytes;while(true){try {bytes = mmInStream.read(buffer);if (bytes > 0) {for (int i = 0; i < bytes; i++) {Byte c = buffer[i];mRx.add(c);// line end or bootloader endif ((c == 0x0a && commMode==MODE_LINE) || (c==0x10 && commMode==MODE_FORWARD)) {// TODO: post msg to UI//write(mReceiveString.getBytes());Byte[] rxbtyes = mRx.toArray(new Byte[mRx.size()]);///*String hexStr="";int[] buf = new int[mRx.size()];for(int i1=0;i1<rxbtyes.length;i1++){hexStr+= String.format("%02X ", rxbtyes[i1]);buf[i1] = rxbtyes[i1];}Log.i("mb", "rx:"+hexStr);//*/mHandler.obtainMessage(MSG_RX,buf).sendToTarget();mRx.clear();}}}} catch (IOException e) {Log.i(dbg, "disconnected");connDev = null;if(mHandler!=null){Message msg = mHandler.obtainMessage(MSG_DISCONNECTED);mHandler.sendMessage(msg);}break;}}}public void write(byte[] bytes){try {txBusy=true;mmOutStream.write(bytes);mmOutStream.flush();txBusy=false;} catch (IOException e) {Log.e(dbg, "Exception during write", e);}}public void cancel(){try {mmSocket.close();} catch (IOException e) {Log.e(dbg, "Exception during cancel", e);}}}public void devListClear(){btDevices.clear();// don't forget the connecting deviceif(connDev!=null){btDevices.add(connDev);}}final BroadcastReceiver mBTDevDiscover = new BroadcastReceiver(){@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();Log.d("mb", "broadcast:"+action);if(BluetoothDevice.ACTION_FOUND.equals(action)){BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//Log.d("mb", "bluetooth found:"+device.getName()+" "+device.getAddress()+" "+device.getBondState()+" "+BluetoothDevice.BOND_NONE+" "+BluetoothDevice.BOND_BONDED);if(btDevices.indexOf(device)==-1){btDevices.add(device);if(mHandler!=null){Message msg = mHandler.obtainMessage(MSG_FOUNDDEVICE);mHandler.sendMessage(msg);}}//bluetoothConnect(device);}else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){}else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){if(mHandler!=null){Message msg = mHandler.obtainMessage(MSG_DISCOVERY_FINISHED);mHandler.sendMessage(msg);}Log.i(dbg,"bluetooth discover finished");}else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){Log.i(dbg,"bluetooth ACTION_STATE_CHANGED:"+mBTAdapter.isEnabled());}else if (action.equals("android.bluetooth.device.action.PAIRING_REQUEST")) {BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);if (device.getBondState() != BluetoothDevice.BOND_BONDED) {//setBluetoothPairingPin(device);}}} };
public List<String> getPairedList(){List<String> data = new ArrayList<String>();Set<BluetoothDevice> pairedDevices = mBTAdapter.getBondedDevices();prDevices.clear();if (pairedDevices.size() > 0) {for (BluetoothDevice device : pairedDevices) {prDevices.add(device);}}for(BluetoothDevice dev : prDevices){String s = dev.getName();s=s+" "+dev.getAddress();if(connDev!=null && connDev.equals(dev)){s="-> "+s;}data.add(s);}return data;}public List<String> getBtDevList(){List<String> data = new ArrayList<String>();Set<BluetoothDevice> pairedDevices = mBTAdapter.getBondedDevices(); // prDevices.clear();if (pairedDevices.size() > 0) {for (BluetoothDevice device : pairedDevices) {if(!btDevices.contains(device))btDevices.add(device);}}for(BluetoothDevice dev : btDevices){String s = dev.getName();if(s!=null){if(s.indexOf("null")>-1){s = "Bluetooth";}}else{s = "Bluetooth";}//String[] a = dev.getAddress().split(":");s=s+" "+dev.getAddress()+" "+(dev.getBondState()== BluetoothDevice.BOND_BONDED?((connDev!=null && connDev.equals(dev))?getString(R.string.connected):getString(R.string.bonded)):getString(R.string.unbond));data.add(s);} return data; } public void bluetoothWrite(byte[] data){if(mConnectedThread==null) return;///*String hexStr="";for(int i1=0;i1<data.length;i1++){hexStr+= String.format("%02X ", data[i1]);}Log.d("mb", "tx:"+hexStr);//*/if(mConnectedThread.txBusy==false){mConnectedThread.write(data);}else{Log.d("mb", "tx busy");}}public void bluetoothDisconnect(BluetoothDevice device){Log.i(dbg, "disconnect to "+device.getName());if(mConnectThread != null){mConnectThread.cancel();mConnectThread = null;}if(mConnectedThread != null){mConnectedThread.cancel();mConnectedThread = null;}}public void bluetoothConnect(BluetoothDevice device) throws Exception {Log.i(dbg, "try connect to "+device.getName());if(mConnectThread != null){mConnectThread.cancel();mConnectThread = null;}if(mConnectedThread != null){mConnectedThread.cancel();mConnectedThread = null;}mConnectThread = new ConnectThread(device);mConnectThread.start(); Intent intent =new Intent(this,DialogActivity.class);intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.putExtra("msg", getString(R.string.connecting));startActivity(intent);}public void bluetoothConnected(BluetoothDevice device, BluetoothSocket socket){Log.i(dbg, "bluetooth connected:"+device.getAddress());connDev = device;if(mHandler!=null){Message msg = mHandler.obtainMessage(MSG_CONNECTED);mHandler.sendMessage(msg);}if(mConnectedThread != null){mConnectedThread.cancel();mConnectedThread = null;}mConnectedThread = new ConnectedThread(socket);mConnectedThread.start();Intent intent =new Intent(this,DialogActivity.class);intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.putExtra("msg", "connected");startActivity(intent);}@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}}
總結
以上是生活随笔為你收集整理的Android项目中Bluetooth类如何写的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java中SeparatedListAd
- 下一篇: Android中Intent和Inten