check if Bluetooth is enabled

master
Zhengyu Peng 3 years ago
parent b3dc1f3fd1
commit 3daa95c276

@ -2,6 +2,8 @@ package com.rookiedev.hexapod
import android.app.Activity
import android.app.AlertDialog
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
@ -39,6 +41,7 @@ class MainActivity : AppCompatActivity() {
private const val ERROR_NO_PERMISSION = 0
private const val ERROR_NO_DEVICE = 1
private const val ERROR_BLUETOOTH_DISABLED = 2
}
private var mContext: Context? = null
@ -115,7 +118,14 @@ class MainActivity : AppCompatActivity() {
// select bluetooth device
selectedDevice.setOnClickListener {
val bluetoothManager =
this.mContext!!.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
val bluetoothAdapter: BluetoothAdapter? = bluetoothManager.adapter
if (bluetoothAdapter != null) {
if (!bluetoothAdapter.isEnabled) {
alertDialog(ERROR_BLUETOOTH_DISABLED)
}
} else {
if (btConnectPermission && btScanPermission) {
val serverIntent = Intent(this, DeviceListActivity::class.java)
resultLauncher.launch(serverIntent)
@ -123,6 +133,7 @@ class MainActivity : AppCompatActivity() {
alertDialog(ERROR_NO_PERMISSION)
}
}
}
if (tabLayout.selectedTabPosition == 0) {
ipLayout.visibility = View.VISIBLE
@ -159,6 +170,14 @@ class MainActivity : AppCompatActivity() {
}
} else if (tabLayout.selectedTabPosition == 1) {
if (btDeviceMac.text.isNotBlank()) {
val bluetoothManager =
this.mContext!!.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
val bluetoothAdapter: BluetoothAdapter? = bluetoothManager.adapter
if (bluetoothAdapter != null) {
if (!bluetoothAdapter.isEnabled) {
alertDialog(ERROR_BLUETOOTH_DISABLED)
}
} else {
if (btConnectPermission && btScanPermission) {
saveSharedPref()
val intent = Intent(this, ControlActivity::class.java).apply {
@ -169,6 +188,7 @@ class MainActivity : AppCompatActivity() {
} else {
alertDialog(ERROR_NO_PERMISSION)
}
}
} else {
alertDialog(ERROR_NO_DEVICE)
}
@ -200,10 +220,8 @@ class MainActivity : AppCompatActivity() {
if (result.resultCode == Activity.RESULT_OK) {
// There are no request codes
val data: Intent? = result.data
btDeviceName.text = data!!.getStringExtra("device_name")
btDeviceMac.text = data.getStringExtra("device_address")
}
}
@ -322,6 +340,18 @@ class MainActivity : AppCompatActivity() {
"OK"
) { _, _ -> }
}
ERROR_BLUETOOTH_DISABLED -> {
alert.setTitle("Bluetooth Disabled")
alert.setIcon(R.drawable.ic_baseline_error_24)
alert.setMessage(
"Please enable Bluetooth in Settings"
)
alert.setOnCancelListener { }
alert.setButton(
AlertDialog.BUTTON_POSITIVE,
"OK"
) { _, _ -> }
}
}
alert.show()
}

Loading…
Cancel
Save