gpt4 book ai didi

android - Android 上的蓝牙 : StartDiscovery not working. 无法扫描设备

转载 作者:行者123 更新时间:2023-12-04 23:52:41 24 4
gpt4 key购买 nike

我是 android 新手,我正在制作一个具有蓝牙功能的应用程序。我可以设置蓝牙适配器,获取我自己的设备信息,但我无法使用 startdiscovery 来发现蓝牙设备。当我开始扫描时,它什么也不做。

我正在使用 onclicklistner 开始扫描:

  bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!(bluetooth.isEnabled())) {
status = "Bluetooth is not Enabled.";
Toast.makeText(AddUser.this, status, Toast.LENGTH_LONG).show();
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);

}
else
{

scand();
}

}

这是我在“public void onCreate”函数之后放置的 onActivityResult 函数:
 protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
System.out.println(resultCode);
if (resultCode == RESULT_CANCELED) {
status="Error Enabling bluetooth";
Toast.makeText(AddUser.this, status, Toast.LENGTH_LONG).show();
} else {

scand();
}



}

这是我的 scand 函数,我在其中调用了 startdiscovery:
    private void scand()
{



bluetooth.startDiscovery();
Log.d("itmes", ""+items.size());
item1 = new String[items.size()];
item1 = items.toArray(item1);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose a device");
builder.setItems(item1, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), item1[item], Toast.LENGTH_SHORT).show();

}

});

AlertDialog alert = builder.create();

alert.show();

}

这是广播接收器:
 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();

if (BluetoothDevice.ACTION_FOUND.equals(action))
{
Log.e("br", "--- device found ---");
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

items.add(device.getName());
}
}
};

在广播接收器的上述代码中,我试图将找到的设备名称放在字符串 ArrayList“items”中。

我在 oncreate 函数中注册广播接收器,如下所示:
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);

我在 androidmanifest 文件中设置了蓝牙权限。在上面的 scand 函数中,它应该显示已发现设备的列表,但它显示的是一个只有标题的空对话框。请告诉我如何正确使用 startdiscovery 和 broadcastreceiver 在 alertdialog 中显示结果。

最佳答案

检查你有

 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

在你的 list 中。


https://developer.android.com/reference/android/bluetooth/BluetoothDevice#ACTION_FOUND

关于android - Android 上的蓝牙 : StartDiscovery not working. 无法扫描设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16184420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com