问题
I need to continuously monitor the bluetooth devices which are present every 5 seconds. I have written the following piece of code which is not working for me.
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();
}
What code needs to be added to this so that the aplication works fine.Note that I need to monitor the bluetooth devices every 5 seconds.
回答1:
You can use the Timer and TimerTask for continuously checking that particular device is available or not.
For example:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask {
@Override
public void run () {
//Here you can use handler or whatever you want to use.
}
},delay, period);
delay - amount of time in milliseconds before first execution.
period - amount of time in milliseconds between subsequent executions.
http://developer.android.com/reference/java/util/Timer.html#scheduleAtFixedRate
Refer this link for more details.
来源:https://stackoverflow.com/questions/13297479/continuously-tracing-the-available-bluetooth-connections-in-the-mobiles-vicinit