无法扫描蓝牙设备

时间:2014-11-04 09:27:58

标签: android

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

这是我的代码段

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);
}   

}

1 个答案:

答案 0 :(得分:0)

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

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