Android经典蓝牙连接
生活随笔
收集整理的這篇文章主要介紹了
Android经典蓝牙连接
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
記錄下連接經典藍牙遇到的坑。
一些基本概念資料很多,這里直接上代碼,里面都有注釋和一些關鍵點。
整個類如下:
import android.app.Activity; import android.bluetooth.BluetoothA2dp; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Handler;import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;/*** * time:2022/2/15*/ public class BleControlTool {private static BleControlTool mInstance;private BluetoothAdapter mBluetoothAdapter;private BluetoothReceiver mReceiver;private BluetoothDevice mDeviceResult; //連接的設備private BluetoothA2dp mBluetoothA2dp; //高級音頻傳輸協議private Activity mActivity;private BleControlTool() {}public static BleControlTool getInstance() {if (mInstance == null) {synchronized (BleControlTool.class) {if (mInstance == null) {mInstance = new BleControlTool();}}}return mInstance;}public void startBlueToothConnect(Activity activity) {mActivity = activity;mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();if (!mBluetoothAdapter.isEnabled()) {mBluetoothAdapter.enable();}IntentFilter intentFilter = new IntentFilter();intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//發現設備intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//配對intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//搜索結束//注意,有些設備連接狀態是這個廣播,我就是栽在這里,一臺設備是這里的回調,有些設備又是下面的廣播回調,所以要做兼容...intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);//注意,有些設備連接狀態又是這個廣播,intentFilter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);mReceiver = new BluetoothReceiver();mActivity.registerReceiver(mReceiver, intentFilter);mBluetoothAdapter.getProfileProxy(mActivity, new BluetoothProfile.ServiceListener() {@Overridepublic void onServiceConnected(int profile, BluetoothProfile proxy) {MagicLog.e("-----onServiceConnected1");if (profile == BluetoothProfile.A2DP) {//Service連接成功,獲得BluetoothA2DPMagicLog.e("-----onServiceConnected2");mBluetoothA2dp = (BluetoothA2dp) proxy;//獲取到 mBluetoothA2dp 后才開始掃描,如果藍牙沒有預先打開,這里會先執行,mBluetoothAdapter.enable()調用之后,這做一個延時new Handler().postDelayed(new Runnable() {@Overridepublic void run() {//開始掃描startDiscovery();}}, 5000);//這里可以做已經配對過的設備可以直接進行連接,本人沒有做具體處理測試,可自行做。/*Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices();for (BluetoothDevice device : bondedDevices) {MagicLog.d("配對過的 name:" + device.getName() + " mac:" + device.getAddress());if (device.getName().contains("Self")) {mDeviceResult = device;connectClassic(device);}}*/}/*List<BluetoothDevice> mDevices = proxy.getConnectedDevices();if (mDevices != null) {for (int i = 0; i < mDevices.size(); i++) {System.out.println("---連接上的設備:" + mDevices.get(i).getName() + "---" + mDevices.get(i).getAddress());}}*/}@Overridepublic void onServiceDisconnected(int profile) {MagicLog.e("-----onServiceDisconnected3");}}, BluetoothProfile.A2DP);}//藍牙廣播接收數據private class BluetoothReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {if (mActivity.isFinishing()) {MagicLog.d("-----------return");return;}if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);if (device == null) {return;}MagicLog.d("掃描到可連接的藍牙設備 name:" + device.getName() + " mac:" + device.getAddress());if (!TigerUtil.isEmpty(device.getName())) {if (device.getName().contains("Selfie")) {mDeviceResult = device;createBond();}}} else if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(intent.getAction())) {MagicLog.d("-=-==============BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED");int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, -1);MagicLog.d("=======state:" + state);switch (state) {case BluetoothAdapter.STATE_CONNECTING:MagicLog.d("=======STATE_CONNECTING");break;case BluetoothAdapter.STATE_CONNECTED:MagicLog.d("=======STATE_CONNECTED,連接成功就銷毀,這里銷毀也是關鍵");destroyBT();break;case BluetoothAdapter.STATE_DISCONNECTED:MagicLog.d("=======STATE_DISCONNECTED");break;}} else if (BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED.equals(intent.getAction())) {MagicLog.d("=-------BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED");BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);switch (intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, -1)) {case BluetoothA2dp.STATE_CONNECTING:BluetoothDevice deviceC = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);MagicLog.d("=====連接中: " + deviceC.getName() + " connecting");break;case BluetoothA2dp.STATE_CONNECTED:MagicLog.d("=====連接成功 device: " + device.getAddress() + " connected");destroyBT();break;case BluetoothA2dp.STATE_DISCONNECTING:MagicLog.d("=====連接斷開 device: ");break;case BluetoothA2dp.STATE_DISCONNECTED:MagicLog.d("=====連接斷開2 device: ");//進行重連break;default:break;}} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(intent.getAction())) {int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE);BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);if (device == null) {return;}switch (bondState) {case BluetoothDevice.BOND_BONDED: //配對成功MagicLog.d("=====配對ok Device:" + device.getAddress() + " bonded.");connectClassic(); //連接藍牙設備break;case BluetoothDevice.BOND_BONDING:MagicLog.d("=====配對中 Device:" + device.getAddress() + " bonding.");break;case BluetoothDevice.BOND_NONE:MagicLog.d("=====配對失敗 Device:" + device.getAddress() + " not bonded.");//不知道是藍牙耳機的關系還是什么原因,經常配對不成功//配對不成功的話,重新嘗試配對createBond();break;default:break;}} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(intent.getAction())) {System.out.println("------掃描結束");}}}private void createBond() {if (mDeviceResult != null) {MagicLog.d("-----createBond");mDeviceResult.createBond();}}private void startDiscovery() {if (mBluetoothAdapter != null) {mBluetoothAdapter.startDiscovery();}}private void cancelDiscovery() {if (mBluetoothAdapter != null) {mBluetoothAdapter.cancelDiscovery();}}private void connectClassic() {try {if (mBluetoothA2dp == null) {return;}//這里用反射連接Method method = mBluetoothA2dp.getClass().getMethod("connect", BluetoothDevice.class);//method.setAccessible(true);method.invoke(mBluetoothA2dp, mDeviceResult);MagicLog.d("直接開始連接經典blue----------connectClassic-");} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {e.printStackTrace();}}public void destroyBT() {if (mBluetoothAdapter != null && mBluetoothA2dp != null) {mBluetoothAdapter.closeProfileProxy(BluetoothProfile.A2DP, mBluetoothA2dp);mBluetoothA2dp = null;mBluetoothAdapter = null;}if (mActivity != null) {mActivity.unregisterReceiver(mReceiver);mActivity = null;}}}正常一般上面的步驟就差不多了,但是有些藍牙設備是奇奇怪怪的,比如我的:
?看到紅圈沒有,他是個鍵盤圖標,連接成功后,發現Activity重新創建了,那就要在清單文件加上,這也是個坑:
android:configChanges="keyboard|keyboardHidden|navigation"android:screenOrientation="portrait"總結
以上是生活随笔為你收集整理的Android经典蓝牙连接的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网络存储服务器dsm系统,群晖nas网络
- 下一篇: 凯恩斯乘数到底有多么神奇?