我试图在我的应用程序上发现可用的蓝牙设备,但它不起作用,我认为问题出在我的广播接收器上。有人可以告诉我这个广播接收器出了什么问题吗:
package com.example.wheelchairapp;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class AvailableBroadcaseReciever extends BroadcastReceiver {
RecyclerView.Adapter adapter2;
public AvailableBroadcaseReciever(RecyclerView.Adapter adapter2) {
this.adapter2 = adapter2;
}
@Override
public void onReceive(Context context, @NonNull Intent intent) {
if(BluetoothDevice.ACTION_FOUND.equals(intent.getAction())){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
return;
}
DevicesList.availableDevices.add(device.getName());
adapter2.notifyDataSetChanged();
}
}
}
我尝试完全遵循 YouTube 开发人员的要求,但问题没有解决。
我不确定,也许你的权限有问题
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.RecyclerView;
public class AvailableBroadcaseReciever extends BroadcastReceiver {
RecyclerView.Adapter adapter2;
public AvailableBroadcaseReciever(RecyclerView.Adapter adapter2) {
this.adapter2 = adapter2;
}
@Override
public void onReceive(Context context, Intent intent) {
if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Check for BLUETOOTH permission
if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
// Request the missing permission
// Do something here like requesting the permission or notifying the user
// This is just an example, you may want to handle this differently based on your app's requirements
Toast.makeText(context, "Bluetooth permission not granted", Toast.LENGTH_SHORT).show();
return;
}
// You may also want to check for null device.getName() before adding it to the list
if(device != null && device.getName() != null) {
DevicesList.availableDevices.add(device.getName());
adapter2.notifyDataSetChanged();
}
}
}
}
确保您还在应用程序的清单文件中请求了必要的权限。你应该有这样的东西:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
这些权限是发现蓝牙设备并与之交互所必需的。如果您的应用程序面向 Android 6.0(API 级别 23)或更高版本,请确保在运行时也请求这些权限。
问题是我没有使用: 导入android.Manifest, 这就是我收到错误的原因 “无法解析符号” 当我尝试添加权限时