日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android项目中Bluetooth类如何写

發布時間:2025/4/16 Android 51 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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權限


首先,該導的包,該聲明的常量,變量,對象等,如下

import android.annotation.SuppressLint; import android.app.Service; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.util.Log;import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID;@SuppressLint("NewApi") public class Bluetooth extends Service {static final String dbg = "bluetooth";static final int MSG_CONNECTED=1;static final int MSG_DISCONNECTED=2;static final int MSG_RX = 3;static final int MSG_FOUNDDEVICE = 4;static final int MSG_CONNECT_FAIL = 5;static final int MSG_DISCOVERY_FINISHED = 6;static final int MSG_RX_FIRMUPLOAD = 7;static final int REQUEST_CONNECT_DEVICE = 1;static final int REQUEST_ENABLE_BT = 2;BluetoothAdapter mBTAdapter;static final String BTName = "BTMakeblock";static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");BluetoothDevice connDev;ConnectThread mConnectThread;ConnectedThread mConnectedThread;ArrayList<BluetoothDevice> btDevices;ArrayList<BluetoothDevice> prDevices; // paired bt devices//public ArrayAdapter<String> devAdapter;Handler mHandler;static final int MODE_LINE = 0;static final int MODE_FORWARD = 1;public int commMode = MODE_LINE;private static Bluetooth _instance;

開始構建管理共享的方法:


public static Bluetooth sharedManager() {if (_instance == null) {_instance = new Bluetooth();}return _instance;}以及Bluetooth()和onCreate()方法

public Bluetooth(){// bluetooth classicbtDevices = new ArrayList<BluetoothDevice>();prDevices = new ArrayList<BluetoothDevice>();mBTAdapter = BluetoothAdapter.getDefaultAdapter();if(mBTAdapter==null){Log.i(dbg, "blue tooth not support");}}@Overridepublic void onCreate() {IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);registerReceiver(mBTDevDiscover,filter);filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);registerReceiver(mBTDevDiscover,filter); _instance = this;if(!mBTAdapter.isEnabled()){mBTAdapter.enable();}else{startDiscovery();}}銷毀方法:

public void onDestroy() {unregisterReceiver(mBTDevDiscover);} public void startDiscovery(){mBTAdapter.startDiscovery();}public boolean isDiscovery(){return mBTAdapter.isDiscovering();}public boolean isEnabled(){return mBTAdapter.isEnabled();}以下是連接線程的方法:

private class ConnectThread extends Thread {private BluetoothSocket mmSocket = null;private BluetoothDevice mmDevice = null;public ConnectThread(BluetoothDevice device){mmDevice = device;}public void run(){// stop discovery, otherwise the pair window won't popupmBTAdapter.cancelDiscovery();try {mmSocket = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);mmSocket.connect();} catch (IOException e) {try {Method m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});Object[] params = new Object[] {Integer.valueOf(1)};mmSocket = (BluetoothSocket)m.invoke(mmDevice, params);mmSocket.connect();} catch (IOException err) {Log.d("mb", "connect:"+err.getMessage());e.printStackTrace();try {mmSocket.close();} catch (IOException e1) {e1.printStackTrace();}if(mHandler!=null){Message msg = mHandler.obtainMessage(MSG_CONNECT_FAIL);mHandler.sendMessage(msg);}} catch (IllegalAccessException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (IllegalArgumentException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (InvocationTargetException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (NoSuchMethodException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}return;}// start connection manager in another threadbluetoothConnected(mmDevice,mmSocket);}public void cancel(){try {mmSocket.close();} catch (IOException e) {e.printStackTrace();}}}

接下來就是處理已連接的線程:

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类如何写的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。