在我的应用程序中,我需要连接一些蓝牙设备并向其发送一些字符串数据。所以我生成一个动作栏项目,通过点击它,一些步骤累积: 1.蓝牙开启(如果关闭) 2.设备设置为可发现 3.通过一些延迟,屏幕上会显示配对设备列表。
现在我的问题是:“如何将我的手机连接到配对列表?!” 我知道我应该使用setOnItemClickListener,但是如何?如果我应该为“CONNECT”生成一些功能?这是我的代码:
在MainActivity中:
private BluetoothAdapter BA;
private Set<BluetoothDevice>pairedDevices;
ListView lv;
on onCreate:
BA = BluetoothAdapter.getDefaultAdapter();
在我的onOptionsItemSelected:
中case R.id.action_bluetooth:
if (!BA.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(),"Bluetooth Turned on",Toast.LENGTH_LONG).show();
}
new CountDownTimer(2000, 1000) {
public void onFinish() {
Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible, 0);
}
public void onTick(long millisUntilFinished) {
}
}.start();
new CountDownTimer(10000, 1000) {
public void onFinish() {
// When timer is finished
// Execute your code here
showBluetoothListView();
}
public void onTick(long millisUntilFinished) {
}
}.start();
return true;
在函数showBluetoothListView()中:
public void showBluetoothListView (){
final Dialog d = new Dialog(MainActivity.this);
d.setTitle("Bluetooth Paired Devices");
d.setContentView(R.layout.bluetooth_list);
final ListView lv = (ListView) d.findViewById(R.id.bluetoothlistView);
pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices)
list.add(bt.getName());
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
d.show();
}