找不到任何蓝牙设备



我目前正在学习蓝牙技术的基础知识。代码是从一些教程我发现,它不工作。我尝试了许多教程中的代码,但我找不到任何蓝牙设备。我想知道是代码有问题,还是我的手机有问题(我还没有在不同的设备上尝试过)。我是用Java写的。我不确定,但我认为功能onReceive有问题,因为它不显示日志消息。

下面是我的代码:

public class MainActivity extends AppCompatActivity {
ListView lv;
BroadcastReceiver mBroadcastReceiver;
BluetoothAdapter mBluetoothAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = findViewById(R.id.listview);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

if (mBluetoothAdapter == null) {
Toast.makeText(this, "BT not supported", Toast.LENGTH_SHORT).show();
} else {
if (!mBluetoothAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "asdasd", Toast.LENGTH_SHORT).show();
}
startActivityForResult(intent, 1);
}
}

}
@Override
protected void onResume(){
super.onResume();
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},2);
}
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},4);
}
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.BLUETOOTH_ADMIN)!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.BLUETOOTH_ADMIN},3);
}
ArrayList<String> arrayList =new ArrayList<>();

mBluetoothAdapter.startDiscovery();


mBroadcastReceiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
if(action.equals(BluetoothDevice.ACTION_FOUND)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i("Bluetooth DEVICES ",device.getName());
}
if(arrayList.size()!=0) {
ArrayAdapter<String> itemAdapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, arrayList);
lv.setAdapter(itemAdapter);
}
}
};
IntentFilter intentFilter =new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver,intentFilter);
}
@Override
protected  void onDestroy(){
super.onDestroy();
unregisterReceiver(mBroadcastReceiver);
}
}

打开蓝牙,然后重新加载代码。如果不是,那么你的蓝牙设备或连接器工作不正常。

最新更新