【问题标题】:Not able to scan bluetooth devices无法扫描蓝牙设备
【发布时间】:2014-11-04 09:27:58
【问题描述】:

我正在开发一个应用程序来扫描蓝牙设备并将它们全部列出。我的要求是我必须在应用程序启动后立即扫描设备..现在我的问题是当我第一次运行应用程序时它只打开蓝牙但不扫描设备.. 我可以在屏幕上看到蓝牙图标,但在蓝牙适配器的 log cat getState() 方法中,状态显示为 STATE_OFF。 请任何人帮助我解决这个问题??

这是我的代码 sn-p

public class MainActivity extends Activity {

private BluetoothAdapter bluetoothAdapter;
Set<String> BTList;
ArrayAdapter<String> BTAdapter;
private ListView listView;
 private BroadcastReceiver mReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    listView = (ListView) findViewById(R.id.listView1);

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if (bluetoothAdapter == null)
        Toast.makeText(this, "Devices does not support Bluetooth",
                Toast.LENGTH_SHORT).show();

    if (!bluetoothAdapter.isEnabled())
        bluetoothAdapter.enable();

    if(bluetoothAdapter.isEnabled()) {
        if(bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
    }

    bluetoothAdapter.startDiscovery();

    mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                 BTAdapter.add(device.getName() + "\n" + device.getAddress());
                 BTAdapter.notifyDataSetChanged();

            }
        }
    };


    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(mReceiver, filter);

    BTAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_expandable_list_item_1);
    listView.setAdapter(BTAdapter);     
}



@Override
protected void onDestroy() {
    super.onDestroy();
    //if(bluetoothAdapter != null) 
    //  bluetoothAdapter.cancelDiscovery();
unregisterReceiver(mReceiver);
}   

}

【问题讨论】:

  • 先学习一些编码。
  • @Ankit 是的,这就是我正在尝试的......这就是我问这个的原因......
  • 你不能只在onCreate中添加所有内容,先学习基础知识。这个问题本身就解决了。

标签: android


【解决方案1】:

如果您有以下条目,请检查您的 AndroidManifest.xml 文件

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2014-09-04
    相关资源
    最近更新 更多