0

我正在构建一个 android 蓝牙聊天应用程序并在其中遇到一些问题。我的问题是:我无法检测到范围内可用的蓝牙设备,也无法在列表中显示。因为我是 android 编程新手,无法检测到问题。请帮帮我。

我的代码是:

public class BluetoothSearchActivity extends Activity {

    ArrayAdapter<String> btArrayAdapter;
    BluetoothAdapter mBluetoothAdapter;
    TextView stateBluetooth;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ImageView BluetoothSearchImageView=new ImageView(this);
        BluetoothSearchImageView.setImageResource(R.drawable.inner1);

        setContentView(BluetoothSearchImageView);
        setContentView(R.layout.activity_bluetooth_search);

        mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();

        ListView listDevicesFound=(ListView) findViewById(R.id.myList);

        btArrayAdapter=new ArrayAdapter<String> (BluetoothSearchActivity.this,android.R.layout.simple_list_item_1);

        listDevicesFound.setAdapter(btArrayAdapter);

        registerReceiver(ActionFoundReceiver,new IntentFilter(BluetoothDevice.ACTION_FOUND));

        btArrayAdapter.clear();
        mBluetoothAdapter.startDiscovery();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(ActionFoundReceiver);
    }

    private final BroadcastReceiver ActionFoundReceiver=new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action=intent.getAction();
            if(BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                btArrayAdapter.add(device.getName()+"\n"+device.getAddress());
                btArrayAdapter.notifyDataSetChanged();
            }
        }   
    };
4

1 回答 1

0

您是否将其他设备设置为可发现?默认情况下,大多数智能手机对于配对设备是不可见的,您需要启用可见性才能使其可见。

我看到您使用 API 参考中的示例,因此它应该可以工作。

确保你有:

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

在 AndroidManifest.xml 文件中。

除此之外,您的对象还有一些奇怪的命名约定。ActionFoundReceiver 应该是 actionFoundReceiver (它是一个对象而不是一个类),但没什么大不了的。

如果您收到任何类型的错误消息,请同时发布。

编辑:您可以在 Log.d(tag, string) 中写出设备名称和地址,以便您可以在 logcat 调试中读出它,从而消除显示列表的问题。

编辑:为 Log.d 添加代码

import android.util.Log;

//to use Log.d(String, String)
Log.d("someTag", "your text here");

您可以使用 Log.d 打印调试信息,帮助您了解代码是否正确执行。我想 Log.d("tag", device.getName()+" "+device.getAddress());看看你是否得到听众的任何回应。并消除您尝试将其放入列表等时可能遇到的任何问题。

——托马斯·弗洛洛

于 2012-10-24T06:53:16.860 回答