Android studio AndroidStudio Kotlin连接到蓝牙
我已将Android studio AndroidStudio Kotlin连接到蓝牙,android-studio,kotlin,Android Studio,Kotlin,我已将添加到清单中,但错误 缺少BluetoothAdapter所需的权限。已启用:android.permission.BLUETOOTH。 仍然存在 另外,在ContextCompat.checkSelfPermission(…)中,第一个参数CONTEXT是什么?文件没有说 当应用程序未被使用时,我需要断开并重新连接蓝牙,这是否正确 class MainActivity : AppCompatActivity() { var bt: BluetoothAdapter? = nul
添加到清单中,但错误
缺少BluetoothAdapter所需的权限。已启用:android.permission.BLUETOOTH。
仍然存在
另外,在ContextCompat.checkSelfPermission(…)
中,第一个参数CONTEXT
是什么?文件没有说
当应用程序未被使用时,我需要断开并重新连接蓝牙,这是否正确
class MainActivity : AppCompatActivity() {
var bt: BluetoothAdapter? = null
var bts: BluetoothSocket? = null
val REQUEST_BLUETOOTH_PERMISSION: Int = 1
val REQUEST_BLUETOOTH_ENABLE: Int = 2
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE))
{
Toast.makeText(
getApplicationContext(),
"Device does not support Bluetooth therefore this application cannot run.",
Toast.LENGTH_SHORT
).show();
return;
}
bt = BluetoothAdapter.getDefaultAdapter()
if (bt == null) {
// This device does not have Bluetooth.
Toast.makeText(
getApplicationContext(),
"Device does not have a Bluetooth adapter therefore this application cannot run.",
Toast.LENGTH_SHORT
).show();
return;
}
bluetoothConnect();
}
fun bluetoothConnect() {
if (ContextCompat.checkSelfPermission(
CONTEXT, // What is this? It's not explained at https://developer.android.com/training/permissions/requesting
Manifest.permission.BLUETOOTH
) == PackageManager.PERMISSION_GRANTED
) {
if (bt.isEnabled == false) { // Error: Missing permission required by BluetoothAdapter.isEnabled: android.permission.BLUETOOTH.
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_BLUETOOTH_ENABLE)
} else {
val pairedDevices: Set<BluetoothDevice>? = bt.bondedDevices
pairedDevices?.forEach { device ->
val deviceName = device.name
val deviceHardwareAddress = device.address // MAC address
}
}
}
else {
// Request permission. That will call back to onActivityResult which in the case of success will call this method again.
// Ask for permission.
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.BLUETOOTH),
REQUEST_BLUETOOTH_PERMISSION
)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_BLUETOOTH_PERMISSION) {
if (resultCode == RESULT_OK) {
bluetoothConnect();
} else {
Toast.makeText(
getApplicationContext(),
"This application cannot run because it does not have Bluetooth permission.",
Toast.LENGTH_SHORT
).show();
// Do we need to quit? How?
}
}
else if( requestCode == REQUEST_BLUETOOTH_ENABLE)
{
if(resultCode == RESULT_OK)
{
// try again
bluetoothConnect();
}
else {
Toast.makeText(
getApplicationContext(),
"This application cannot run because Bluetooth is not enabled and could not be enabled.",
Toast.LENGTH_SHORT
).show();
// Do we need to quit? How?
}
}
}
override fun onPause() {
super.onPause()
// Release Bluetooth
}
override fun onResume() {
super.onResume()
// Connect Bluetooth
}
override fun onStop() {
super.onStop()
// Release Bluetooth
}
override fun onStart() {
super.onStart()
// Connect Bluetooth
}
}
class MainActivity:AppCompatActivity(){
var bt:BluetoothAdapter?=null
var bts:BluetoothSocket?=null
val请求\蓝牙\权限:Int=1
val请求\蓝牙\启用:Int=2
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
如果(!getPackageManager().hasSystemFeature(PackageManager.FEATURE\u BLUETOOTH\u LE))
{
Toast.makeText(
getApplicationContext(),
“设备不支持蓝牙,因此此应用程序无法运行。”,
吐司长度
).show();
返回;
}
bt=BluetoothAdapter.getDefaultAdapter()
if(bt==null){
//此设备没有蓝牙。
Toast.makeText(
getApplicationContext(),
“设备没有蓝牙适配器,因此此应用程序无法运行。”,
吐司长度
).show();
返回;
}
bluetoothConnect();
}
有趣的蓝牙连接(){
if(ContextCompat.checkSelfPermission(
上下文,//这是什么?这里没有解释https://developer.android.com/training/permissions/requesting
Manifest.permission.BLUETOOTH
)==已授予PackageManager.PERMISSION\u权限
) {
if(bt.isEnabled==false){//错误:BluetoothAdapter.isEnabled缺少所需的权限:android.permission.BLUETOOTH。
val enablebtent=Intent(BluetoothAdapter.ACTION\u REQUEST\u ENABLE)
startActivityForResult(启用BTIntent、请求\蓝牙\启用)
}否则{
val pairedDevices:设置?=bt.bondedDevices
pairedDevices?.forEach{device->
val deviceName=device.name
val deviceHardwareAddress=device.address//MAC地址
}
}
}
否则{
//请求权限。这将回调onActivityResult,如果成功,它将再次调用此方法。
//请求许可。
ActivityCompat.requestPermissions(
这
arrayOf(清单、许可、蓝牙),
请求\u蓝牙\u许可
)
}
}
重写activityResult(请求代码:Int,结果代码:Int,数据:Intent?){
super.onActivityResult(请求代码、结果代码、数据)
if(requestCode==请求权限){
if(resultCode==RESULT\u OK){
bluetoothConnect();
}否则{
Toast.makeText(
getApplicationContext(),
“此应用程序无法运行,因为它没有蓝牙权限。”,
吐司长度
).show();
//我们需要辞职吗?怎么辞职?
}
}
else if(requestCode==请求\蓝牙\启用)
{
if(resultCode==RESULT\u OK)
{
//再试一次
bluetoothConnect();
}
否则{
Toast.makeText(
getApplicationContext(),
“此应用程序无法运行,因为蓝牙未启用且无法启用。”,
吐司长度
).show();
//我们需要辞职吗?怎么辞职?
}
}
}
覆盖暂停(){
super.onPause()
//释放蓝牙
}
重写onResume(){
super.onResume()
//连接蓝牙
}
覆盖桌面上的乐趣(){
super.onStop()
//释放蓝牙
}
覆盖有趣的onStart(){
super.onStart()
//连接蓝牙
}
}
编辑:
- 在代码中添加了额外的BT检查
- 添加舱单
正因为评论不利于此,让我给你一个清单,列出你在使用蓝牙之前应该做的事情。(很抱歉,这是用Java编写的,因为这是我现在所拥有的,但是如果需要的话,很容易翻译成Kotlin) 我这样做是为了BT-LE(低能量),这是。。显而易见的原因
BluetoothAdapter
:
BluetoothAdapter bluetoothAdapter = manager.getAdapter();
所有这些在onCreate中都很好,但请记住,每次用户恢复活动时,您都必须检查BT是否已启用(因为它可能已被关闭/禁用/撤销等)
很可能在简历中:
// obviously, you need to check that Bt adapter isn't null and all that,
// otherwise you ought to go back and "construct" it again, check permissions, etc.
adapter = getBTAdapter(); // do all the checks in there...
boolean bluetoothEnabled = adapter != null && adapter.isEnabled();
如果BT收音机关闭(用户将其关闭),您可以通过编程方式启用它,如果您拥有相应的权限(我认为是BT管理员或类似权限,您必须搜索该权限,因为已经有一段时间了)
我想是的
由于BT是一种需要电源的收音机,因此需要一段时间(秒)才能打开并可用。为此,您需要使用另一个广播接收器“收听”
换句话说,该活动将触发一个意图(startActivityForResult(…)
)告诉Android启用BT,您将订阅该广播以收听回调
// Does BLE exist?
if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
final BluetoothManager manager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter bluetoothAdapter = manager.getAdapter();
// obviously, you need to check that Bt adapter isn't null and all that,
// otherwise you ought to go back and "construct" it again, check permissions, etc.
adapter = getBTAdapter(); // do all the checks in there...
boolean bluetoothEnabled = adapter != null && adapter.isEnabled();
public void onReceive(Context context, Intent intent) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE);
switch (state) {
case BluetoothAdapter.STATE_OFF:
case BluetoothAdapter.STATE_TURNING_OFF:
case BluetoothAdapter.STATE_TURNING_ON:
case BluetoothAdapter.STATE_ON:
}
public void onScan(final BluetoothDevice device, int rssi, byte[] record);
public void onScanResult(int callbackType, ScanResult scanResult) {
int rssi = result.getRssi();
BluetoothDevice device = result.getDevice();
String advertiseName = device.getName();
String macAddress = device.getAddress();
BluetoothDevice device = adapter.getRemoteDevice(macAddress);
device.connectGatt(context, false, anotherCallback);
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH"
private lateinit var binding: ActivityMainBinding
private var myBluetooth:BluetoothAdapter? = null
lateinit var mypairedDevices:Set<BluetoothDevice>
val Request_Enable_Blutooth=1
companion object {
val EXTRA_ADDRESS :String= "Device_Address"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
myBluetooth= BluetoothAdapter.getDefaultAdapter()
if (myBluetooth == null)
{
Toast.makeText(applicationContext, "Bluetooth Device Not Available", Toast.LENGTH_LONG).show()
}
if (!myBluetooth!!.isEnabled)
{
val enableBlutoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBlutoothIntent, Request_Enable_Blutooth)
}
binding.BTNPairedDevices.setOnClickListener {
pairedDeviceList()
}
}
private fun pairedDeviceList (){
mypairedDevices = myBluetooth!!.bondedDevices
val list : ArrayList<BluetoothDevice> = ArrayList()
if (!mypairedDevices.isEmpty())
{
for ( device:BluetoothDevice in mypairedDevices)
list.add(device)
//list.add(device.name() + "\n" + device.address())
Log.i("Device", "This is messeage")
}
else {
Toast.makeText(applicationContext, " NO PAIRED DEVICES FOUND", Toast.LENGTH_LONG).show()
}
val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, list)
binding.DeviceListView.adapter = adapter
binding.DeviceListView.onItemClickListener = AdapterView.OnItemClickListener{ _, _, position, _ ->
val device: BluetoothDevice = list[position]
val address: String = device.address
val intent = Intent(this, LedController::class.java)
intent.putExtra(EXTRA_ADDRESS, address)
startActivity(intent)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == Request_Enable_Blutooth)
{
if(resultCode ==Activity.RESULT_OK)
{
if (myBluetooth!!.isEnabled)
{ Toast.makeText(applicationContext, "Bluetooth Enabled", Toast.LENGTH_LONG).show()
}
else ( Toast.makeText(applicationContext, "Bluetooth Disabled", Toast.LENGTH_LONG).show()
)
}
} else if(resultCode == Activity.RESULT_CANCELED)
Toast.makeText(applicationContext, "Bluetooth has been canceled", Toast.LENGTH_LONG).show()
}
}