我需要持续监控每 5 秒出现一次的蓝牙设备。我编写了以下不适合我的代码。
private static final int DISCOVERY_REQUEST = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_connection);
final TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText("");
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
.getDefaultAdapter();
mBluetoothAdapter.startDiscovery();
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
tv.append(device.getName() + "-"
+ /* device.getAddress()+ */"\n");
tv.append("here");
/*
* if (device.getName().equals("ONCEWASCUT-L7")) {
* tv.append("this is in the vicinity");
*
* }
*/
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
.equals(action)) {
tv.append("\nEntered the Finished\n ");
mBluetoothAdapter.startDiscovery();
}
}
};
String aDiscoverable = BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE;
startActivityForResult(new Intent(aDiscoverable), DISCOVERY_REQUEST);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
mBluetoothAdapter.startDiscovery();
}
需要添加什么代码才能使应用程序正常工作。请注意,我需要每 5 秒监控一次蓝牙设备。