diff --git a/app/src/main/java/world/shanya/serilportsample/MainActivity.kt b/app/src/main/java/world/shanya/serilportsample/MainActivity.kt index ab3ccd1..5fd365d 100644 --- a/app/src/main/java/world/shanya/serilportsample/MainActivity.kt +++ b/app/src/main/java/world/shanya/serilportsample/MainActivity.kt @@ -21,7 +21,8 @@ class MainActivity : AppCompatActivity() { setContentView(R.layout.activity_main) val serialPort = SerialPortBuilder .isDebug(true) - .autoConnect(true) + .autoConnect(false) + .setOpenConnectionTypeDialogFlag(true) .setAutoReconnectAtIntervals(false, time = 10000) .setSendDataType(SerialPort.SEND_STRING) .isIgnoreNoNameDevice(false) @@ -64,10 +65,6 @@ class MainActivity : AppCompatActivity() { .build(this) - serialPort.setBleUUID("BLE_UUID") - serialPort.setLegacyUUID("SPP_UUID") - - serialPort.setSendDataType(SerialPort.SEND_HEX) serialPort.setConnectionResultCallback { result, bluetoothDevice -> Log.d("SerialPort", "ConnectionResult: $result") if (bluetoothDevice != null) { @@ -90,9 +87,14 @@ class MainActivity : AppCompatActivity() { serialPort.connectDevice("F8:33:31:A9:A2:94") } + serialPort.setSendDataType(SerialPort.SEND_HEX) + buttonSend.setOnClickListener { // serialPort.sendData("hello\r\n") - serialPort.sendData("你好") + serialPort.sendData("0C fF") +// serialPort.sendData("你好") +// serialPort.printPossibleBleUUID() +// serialPort.doDiscovery(this) } } } \ No newline at end of file diff --git a/serialport/build.gradle b/serialport/build.gradle index fe2726a..9523f54 100644 --- a/serialport/build.gradle +++ b/serialport/build.gradle @@ -49,4 +49,5 @@ dependencies { implementation 'androidx.lifecycle:lifecycle-service:2.3.0' implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.0' implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.0' + implementation 'com.blankj:utilcodex:1.31.0' } \ No newline at end of file diff --git a/serialport/src/main/java/world/shanya/serialport/SerialPort.kt b/serialport/src/main/java/world/shanya/serialport/SerialPort.kt index bb64ca2..2a225ec 100644 --- a/serialport/src/main/java/world/shanya/serialport/SerialPort.kt +++ b/serialport/src/main/java/world/shanya/serialport/SerialPort.kt @@ -5,12 +5,17 @@ import android.bluetooth.* import android.content.Context import android.content.Intent import android.content.IntentFilter +import android.content.pm.PackageManager +import android.os.Build +import androidx.core.app.ActivityCompat +import com.permissionx.guolindev.PermissionX import world.shanya.serialport.connect.* import world.shanya.serialport.connect.SerialPortConnect import world.shanya.serialport.discovery.* import world.shanya.serialport.discovery.SerialPortDiscovery import world.shanya.serialport.service.SerialPortService import world.shanya.serialport.strings.SerialPortToast +import world.shanya.serialport.strings.SerialPortToastBean import world.shanya.serialport.tools.* import world.shanya.serialport.tools.HexStringToString import world.shanya.serialport.tools.LogUtil @@ -65,6 +70,8 @@ class SerialPort private constructor() { const val DISCOVERY_BLE = 0 const val DISCOVERY_LEGACY = 1 + //连接方式选择对话框标志位 + internal var openConnectionTypeDialogFlag = false //传统设备搜索结果广播接收器 internal val discoveryBroadcastReceiver = DiscoveryBroadcastReceiver() @@ -262,7 +269,13 @@ class SerialPort private constructor() { */ internal fun _connectLegacyDevice(device: BluetoothDevice) { newContext?.let { - SerialPortConnect.connectLegacy(it,device.address) + SerialPortConnect.connectLegacy(it, device.address) + } + } + + internal fun _connectBleDevice(device: BluetoothDevice) { + newContext?.let { + SerialPortConnect.connectBle(it, device.address) } } @@ -273,13 +286,15 @@ class SerialPort private constructor() { * @Date 2021-7-21 * @Version 4.0.0 */ - internal fun _connectDevice(device: BluetoothDevice) { + internal fun _connectDevice(device: BluetoothDevice, context: Context) { newContext?.let { + if (device.type == 2) { SerialPortConnect.connectBle(it, device.address) } else { SerialPortConnect.connectLegacy(it, device.address) } + } } @@ -722,8 +737,19 @@ class SerialPort private constructor() { * @Version 4.0.0 */ fun doDiscovery(context: Context) { - SerialPortDiscovery.startLegacyScan(context) - SerialPortDiscovery.startBleScan() + if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission( + context, + android.Manifest.permission.ACCESS_COARSE_LOCATION + ) + ) { + //判断是否以授权相机权限,没有则授权 + LogUtil.log("请先获取定位权限!") + ToastUtil.toast(context, SerialPortToast.permission) + } else { + SerialPortDiscovery.startLegacyScan(context) + SerialPortDiscovery.startBleScan() + } + } /** @@ -742,7 +768,7 @@ class SerialPort private constructor() { * setBleUUID 设置Ble设备UUID * @Author Shanya * @Date 2022-1-12 - * @Version 4.2.0 + * @Version 4.1.4 */ fun setBleUUID(uuid: String) { SerialPortConnect.UUID_BLE = uuid @@ -753,10 +779,21 @@ class SerialPort private constructor() { * setLegacyUUID 设置传统设备UUID * @Author Shanya * @Date 2022-1-12 - * @Version 4.2.0 + * @Version 4.1.4 */ fun setLegacyUUID(uuid: String) { SerialPortConnect.UUID_LEGACY = uuid LogUtil.log("设置传统设备UUID", uuid) } + + /** + * 默认连接页面连接方式选择对话框标志位 + * @param status 开启状态 + * @Author Shanya + * @Date 2022-1-12 + * @Version 4.1.4 + */ + fun setOpenConnectionTypeDialogFlag(status: Boolean) { + openConnectionTypeDialogFlag = status + } } \ No newline at end of file diff --git a/serialport/src/main/java/world/shanya/serialport/SerialPortBuilder.kt b/serialport/src/main/java/world/shanya/serialport/SerialPortBuilder.kt index b53c33a..cf19d9a 100644 --- a/serialport/src/main/java/world/shanya/serialport/SerialPortBuilder.kt +++ b/serialport/src/main/java/world/shanya/serialport/SerialPortBuilder.kt @@ -271,47 +271,60 @@ object SerialPortBuilder { return this } - /** - * 获取已配对设备列表 - * @return 已配对设备列表 - * @Author Shanya - * @Date 2021-8-13 - * @Version 4.0.3 - */ - @Deprecated(message = "建议使用 getPairedDevicesListBD", - replaceWith = ReplaceWith( - expression = "getPairedDevicesListBD()")) - fun getPairedDevicesList() = SerialPortDiscovery.pairedDevicesList +// /** +// * 获取已配对设备列表 +// * @return 已配对设备列表 +// * @Author Shanya +// * @Date 2021-8-13 +// * @Version 4.0.3 +// */ +// @Deprecated(message = "建议使用 getPairedDevicesListBD", +// replaceWith = ReplaceWith( +// expression = "getPairedDevicesListBD()")) +// fun getPairedDevicesList() = SerialPortDiscovery.pairedDevicesList +// +// /** +// * 获取未配对设备列表 +// * @return 未配对设备列表 +// * @Author Shanya +// * @Date 2021-8-13 +// * @Version 4.0.3 +// */ +// @Deprecated(message = "建议使用 getUnPairedDevicesListBD", +// replaceWith = ReplaceWith( +// expression = "getUnPairedDevicesListBD()")) +// fun getUnPairedDevicesList() = SerialPortDiscovery.unPairedDevicesList +// +// /** +// * 获取已配对设备列表 +// * @return 已配对设备列表 +// * @Author Shanya +// * @Date 2021-8-13 +// * @Version 4.0.3 +// */ +// fun getPairedDevicesListBD() = SerialPortDiscovery.pairedDevicesListBD +// +// /** +// * 获取未配对设备列表 +// * @return 未配对设备列表 +// * @Author Shanya +// * @Date 2021-8-13 +// * @Version 4.0.3 +// */ +// fun getUnPairedDevicesListBD() = SerialPortDiscovery.unPairedDevicesListBD - /** - * 获取未配对设备列表 - * @return 未配对设备列表 - * @Author Shanya - * @Date 2021-8-13 - * @Version 4.0.3 - */ - @Deprecated(message = "建议使用 getUnPairedDevicesListBD", - replaceWith = ReplaceWith( - expression = "getUnPairedDevicesListBD()")) - fun getUnPairedDevicesList() = SerialPortDiscovery.unPairedDevicesList /** - * 获取已配对设备列表 - * @return 已配对设备列表 - * @Author Shanya - * @Date 2021-8-13 - * @Version 4.0.3 - */ - fun getPairedDevicesListBD() = SerialPortDiscovery.pairedDevicesListBD - - /** - * 获取未配对设备列表 - * @return 未配对设备列表 + * 默认连接页面连接方式选择对话框标志位 + * @param status 开启状态 * @Author Shanya - * @Date 2021-8-13 - * @Version 4.0.3 + * @Date 2022-1-12 + * @Version 4.1.4 */ - fun getUnPairedDevicesListBD() = SerialPortDiscovery.unPairedDevicesListBD + fun setOpenConnectionTypeDialogFlag(status: Boolean):SerialPortBuilder { + SerialPort.openConnectionTypeDialogFlag = status + return this + } /** * 创建实例 diff --git a/serialport/src/main/java/world/shanya/serialport/connect/SerialPortConnect.kt b/serialport/src/main/java/world/shanya/serialport/connect/SerialPortConnect.kt index d6bb3c1..8af9fea 100644 --- a/serialport/src/main/java/world/shanya/serialport/connect/SerialPortConnect.kt +++ b/serialport/src/main/java/world/shanya/serialport/connect/SerialPortConnect.kt @@ -149,13 +149,18 @@ internal object SerialPortConnect { * @param context 上下文 * @param address 设备地址 * @Author Shanya - * @Date 2021-7-21 - * @Version 4.0.0 + * @Date 2022-1-12 + * @Version 4.1.4 */ internal fun connectBle(context: Context, address: String) { + val bluetoothDevice = SerialPort.bluetoothAdapter.getRemoteDevice(address) - bluetoothDevice.connectGatt(context, false, bluetoothGattCallback) + if (bluetoothDevice.type >= 2) { + bluetoothDevice.connectGatt(context, false, bluetoothGattCallback) + } else { + connectedResult(context, false, null, bluetoothDevice) + } } /** @@ -187,20 +192,27 @@ internal object SerialPortConnect { * @param context 上下文 * @param address 设备地址 * @Author Shanya - * @Date 2021-7-21 - * @Version 4.0.0 + * @Date 2022-1-12 + * @Version 4.1.4 */ internal fun _connectLegacy(context: Context, address: String) { var bluetoothDevice:BluetoothDevice ?= null try { bluetoothDevice = SerialPort.bluetoothAdapter.getRemoteDevice(address) - bluetoothSocket = - bluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(UUID_LEGACY)) - bluetoothSocket?.connect() - connectedResult(context, true, null, bluetoothDevice) - inputStream = bluetoothSocket?.inputStream - context.startService(Intent(context, SerialPortService::class.java)) + if (bluetoothDevice.type == BluetoothDevice.DEVICE_TYPE_CLASSIC || + bluetoothDevice.type == BluetoothDevice.DEVICE_TYPE_DUAL + ) { + bluetoothSocket = + bluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(UUID_LEGACY)) + bluetoothSocket?.connect() + connectedResult(context, true, null, bluetoothDevice) + inputStream = bluetoothSocket?.inputStream + context.startService(Intent(context, SerialPortService::class.java)) + } else { + connectedResult(context, false, null, bluetoothDevice) + } + } catch (e: IOException) { e.printStackTrace() connectedResult(context, false, null, bluetoothDevice) diff --git a/serialport/src/main/java/world/shanya/serialport/discovery/DiscoveryActivity.kt b/serialport/src/main/java/world/shanya/serialport/discovery/DiscoveryActivity.kt index 76eb075..4dcfd11 100644 --- a/serialport/src/main/java/world/shanya/serialport/discovery/DiscoveryActivity.kt +++ b/serialport/src/main/java/world/shanya/serialport/discovery/DiscoveryActivity.kt @@ -1,6 +1,7 @@ package world.shanya.serialport.discovery import android.annotation.SuppressLint +import android.app.AlertDialog import android.app.Dialog import android.bluetooth.BluetoothDevice import android.content.Context @@ -19,6 +20,7 @@ import kotlinx.android.synthetic.main.activity_discovery.* import kotlinx.android.synthetic.main.device_cell.view.* import world.shanya.serialport.R import world.shanya.serialport.SerialPort +import world.shanya.serialport.connect.SerialPortConnect import world.shanya.serialport.discovery.SerialPortDiscovery.pairedDevicesListBD import world.shanya.serialport.discovery.SerialPortDiscovery.unPairedDevicesListBD import world.shanya.serialport.strings.SerialPortToast @@ -34,7 +36,7 @@ import world.shanya.serialport.tools.ToastUtil class DiscoveryActivity : AppCompatActivity() { //连接进度对话框 - private lateinit var dialog: Dialog + private lateinit var connectProcessDialog: Dialog /** * Activity创建 @@ -55,9 +57,11 @@ class DiscoveryActivity : AppCompatActivity() { } //初始化连接进度对话框 - dialog = Dialog(this) - dialog.setContentView(R.layout.progress_dialog_layout) - dialog.setCancelable(false) + connectProcessDialog = Dialog(this) + connectProcessDialog.setContentView(R.layout.progress_dialog_layout) + connectProcessDialog.setCancelable(false) + + //搜索状态监听 SerialPortDiscovery.discoveryStatusLiveData.observe(this, Observer { @@ -198,7 +202,7 @@ class DiscoveryActivity : AppCompatActivity() { super.onDestroy() SerialPortDiscovery.stopLegacyScan(this) SerialPortDiscovery.stopBleScan() - dialog.dismiss() + connectProcessDialog.dismiss() LogUtil.log("内置搜索页面销毁") } @@ -225,11 +229,27 @@ class DiscoveryActivity : AppCompatActivity() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DevicesViewHolder { val holder = DevicesViewHolder(inflater.inflate(R.layout.device_cell,parent,false)) holder.itemView.setOnClickListener { - dialog.show() SerialPortDiscovery.stopLegacyScan(this@DiscoveryActivity) SerialPortDiscovery.stopBleScan() val device = SerialPort.bluetoothAdapter.getRemoteDevice(it.textViewDeviceAddress.text.toString()) - SerialPort._connectDevice(device) + if (SerialPort.openConnectionTypeDialogFlag) { + val connectTypeDialog = AlertDialog.Builder(this@DiscoveryActivity) + .setTitle("选择连接方式") + .setItems(R.array.connect_string) { dialog, which -> + connectProcessDialog.show() + if (which == 0) { + SerialPort._connectBleDevice(device) + }else if (which == 1) { + SerialPort._connectLegacyDevice(device) + } + } + .create().show() + }else{ + connectProcessDialog.show() + SerialPort._connectDevice(device, this@DiscoveryActivity) + } + + } return holder } diff --git a/serialport/src/main/java/world/shanya/serialport/tools/SerialPortToolsByKotlin.kt b/serialport/src/main/java/world/shanya/serialport/tools/SerialPortToolsByKotlin.kt index 677be76..c58d362 100644 --- a/serialport/src/main/java/world/shanya/serialport/tools/SerialPortToolsByKotlin.kt +++ b/serialport/src/main/java/world/shanya/serialport/tools/SerialPortToolsByKotlin.kt @@ -1,13 +1,17 @@ package world.shanya.serialport.tools +import android.app.AlertDialog import android.bluetooth.BluetoothDevice import android.content.Context +import android.content.DialogInterface import android.text.TextUtils import android.util.Log import android.widget.Toast import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch +import world.shanya.serialport.R import world.shanya.serialport.SerialPort +import world.shanya.serialport.connect.SerialPortConnect import world.shanya.serialport.strings.SerialPortToast import world.shanya.serialport.strings.SerialPortToastBean import java.io.UnsupportedEncodingException @@ -15,7 +19,6 @@ import java.net.URLEncoder import java.nio.charset.Charset import java.util.* - /** * SPUtil SharePreferences管理类 * @Author Shanya & Se7enOrEleven @@ -217,7 +220,8 @@ object DataUtil { */ fun string2hex(str: String): ArrayList? { val chars = "0123456789ABCDEF".toCharArray() - val stingTemp = str.replace(" ","") + val stringUpper = str.toUpperCase() + val stingTemp = stringUpper.replace(" ","") val bs = stingTemp.toCharArray() var bit = 0 var i = 0 diff --git a/serialport/src/main/res/values/arrays.xml b/serialport/src/main/res/values/arrays.xml new file mode 100644 index 0000000..085fa02 --- /dev/null +++ b/serialport/src/main/res/values/arrays.xml @@ -0,0 +1,7 @@ + + + + BLE连接 + SPP连接 + + \ No newline at end of file