我正在尝试扫描蓝牙设备,但从未调用过寄存器:
public class MainActivity extends Activity {
ArrayList<String> arr_devices = new ArrayList<String>();
ArrayList<String> arr_in_range = new ArrayList<String>();
Button btn_devices;
BluetoothAdapter bluetoothAdapter;
IntentFilter filter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
btn_devices = (Button)findViewById(R.id.search);
btn_devices.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
if (bluetooth != null)
{
if (bluetooth.isEnabled())
{
//this is called
bluetoothAdapter.startDiscovery();
Log.i("State", bluetoothAdapter.getState() + ""); //12 (STATE_ON)
Log.i("Discovery", bluetoothAdapter.isDiscovering() + ""); //FALSE
filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(myreceiver, filter);
//this is where the program stops. No more actions are performed
}
else
{
Toast.makeText(getApplicationContext(), "Bluetooth is not enabled!", Toast.LENGTH_SHORT).show();
}
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myreceiver);
}
final BroadcastReceiver myreceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
//I placed a Log statement here but it doesn't appear in the logcat
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
}
if(BluetoothDevice.ACTION_FOUND.equals(action))
{
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i("device", device.getName() + "\n" + device.getAddress());
}
}};
}
蓝牙已启用。我错过了什么?