Java 在设备之间建立蓝牙连接
我是java新手,目前正在从事一个项目。我已经在我的应用程序中打开和关闭了蓝牙。我还有一个带有配对设备列表的列表视图。我创建了一个“onListItemClick”方法。但是,我似乎不知道如何与配对设备之一建立连接。任何帮助都将不胜感激。多谢各位Java 在设备之间建立蓝牙连接,java,android,eclipse,bluetooth,Java,Android,Eclipse,Bluetooth,我是java新手,目前正在从事一个项目。我已经在我的应用程序中打开和关闭了蓝牙。我还有一个带有配对设备列表的列表视图。我创建了一个“onListItemClick”方法。但是,我似乎不知道如何与配对设备之一建立连接。任何帮助都将不胜感激。多谢各位 import java.util.Set; import android.app.ListActivity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.Blu
import java.util.Set;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Devices extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ArrayAdapter<String> btArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
if(pairedDevices.size()>0){
for (BluetoothDevice device :pairedDevices){
String name = device.getName();
btArrayAdapter.add(name);
}
}
setListAdapter(btArrayAdapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//Here, I want to establish a connection with the device chosen by the user
}
}
import java.util.Set;
导入android.app.ListActivity;
导入android.bluetooth.BluetoothAdapter;
导入android.bluetooth.bluetooth设备;
导入android.os.Bundle;
导入android.view.view;
导入android.widget.ArrayAdapter;
导入android.widget.ListView;
公共类设备扩展了ListActivity{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
//TODO自动生成的方法存根
super.onCreate(savedInstanceState);
ArrayAdapter btArrayAdapter=新的ArrayAdapter(这是android.R.layout.simple\u list\u item\u 1);
BluetoothAdapter btAdapter=BluetoothAdapter.getDefaultAdapter();
Set pairedDevices=btAdapter.getBondedDevices();
如果(pairedDevices.size()>0){
用于(蓝牙设备:pairedDevices){
String name=device.getName();
btArrayAdapter.add(名称);
}
}
setListAdapter(btArrayAdapter);
}
@凌驾
受保护的void onListItemClick(列表视图l、视图v、整数位置、长id){
super.onListItemClick(左、右、位置、id);
//这里,我想与用户选择的设备建立连接
}
}
我给你举了个例子:
public class MainActivity extends Activity{
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ListView PairedListView;
private BluetoothService mBluetoothService = null;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Initialize ArrayAdapter for paired devices
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
PairedListView = (ListView)findViewById(R.id.listView_paired_devices);
PairedListView.setAdapter(mPairedDevicesArrayAdapter);
PairedListView.setOnItemClickListener(this);
getPairedDevices();
}
private void getPairedDevices(){
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
// Add paired devices to ArrayAdapter
// ArrayAdapter will be connected to LisView
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.title_none_paired).toString();
mPairedDevicesArrayAdapter.add(noDevices);
}
}
}
@Override
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBluetoothAdapter.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String adress = info.substring(info.length() -17);
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(adress);
// Attempt to connect to the given bluetooth device in separate thread
// Reason for this is because connecting and sending bytes are blocking calls
mBluetoothService.connect(device);
}
public class BluetoothService {
// Unique UUID for this application
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private BluetoothAdapter mBluetoothAdapter;
public synchronized void connect(BluetoothDevice device){
// Start ConnectThread to connect to given device
mConnectThread = new ConnectThread(device);
mConnectThread.start();
}
private class ConnectThread extends Thread {
private final BluetoothSocket mBluetoothSocket;
private final BluetoothDevice mBluetoothDevice;
public ConnectThread(BluetoothDevice device){
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
mBluetoothDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try{
// MY_UUID is the app's UUID string
tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e){
}
mBluetoothSocket = tmp;
}
public void run(){
// Because BuluetoothAdapter.discovery() is
// heavy weight procedure, cancel any on
// going discovery before attempting to connect
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.cancelDiscovery();
// Connect the device through the socket. This is blocking call so it
// will return on a successful connection or an exception
// Make a connection to the BluetoothSocket
try {
// Connect the device through the socket. This is blocking call so it
// will return on a successful connection or an exception
mBluetoothSocket.connect();
} catch (IOException e) {
try {
// Unable to connect, close the socket and get out
mBluetoothSocket.close();
setState(STATE_CONNECTION_FAILED);
} catch (IOException e1) {
e1.printStackTrace();
}
}
// Reset the ConnectThread because we're done
synchronized (BluetoothService.this) {
mConnectThread = null;
}
// Do work to manage the connection (in a separate thread)
if(mBluetoothSocket.isConnected()){
connected(mBluetoothSocket, mBluetoothDevice); }
}
public void cancel(){
// This method will cancel an in-progress connection and close the socket
try {
mBluetoothSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
公共类MainActivity扩展活动{
私人蓝牙适配器mBluetoothAdapter;
专用阵列适配器MPairedevicesArrayaAdapter;
私有ListView PairedListView;
私有蓝牙服务mBluetoothService=null;
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
//初始化配对设备的ArrayAdapter
MPairedDeviceArrayAdapter=新的ArrayAdapter(这个,R.layout.device\u名称);
PairedListView=(ListView)findViewById(R.id.ListView\u配对设备);
setAdapter(MPairedDeviceArrayaAdapter);
setOnItemClickListener(这个);
getPairedDevices();
}
私有void getPairedDevices(){
//获取一组当前配对的设备
设置pairedDevices=mBluetoothAdapter.getBondedDevices();
//如果存在配对设备,请将每个设备添加到ArrayAdapter
如果(pairedDevices.size()>0){
用于(蓝牙设备:pairedDevices){
//将配对设备添加到ArrayAdapter
//ArrayAdapter将连接到LisView
MPairedDeviceArrayaAdapter.add(device.getName()+“\n”+device.getAddress());
}
}否则{
String NodeDevices=getResources().getText(R.String.title\u none\u paired).toString();
MPairedDeviceArrayaAdapter.add(节点设备);
}
}
}
@凌驾
公共链接(AdapterView av、视图v、内部arg2、长arg3){
//取消发现,因为它成本高昂,而且我们即将连接
mBluetoothAdapter.cancelDiscovery();
//获取设备MAC地址,这是视图中的最后17个字符
字符串信息=((TextView)v.getText().toString();
字符串地址=信息子字符串(信息长度()-17);
BluetoothDevice=mBluetoothAdapter.getRemoteDevice(地址);
//尝试在单独的线程中连接到给定的蓝牙设备
//这是因为连接和发送字节会阻塞调用
mBluetoothService.connect(设备);
}
公共类蓝牙服务{
//此应用程序的唯一UUID
私有静态最终UUID MY_UUID=UUID.fromString(“00001101-0000-1000-8000-00805F9B34FB”);
私有连接线程mConnectThread;
私有连接线程mConnectedThread;
私人蓝牙适配器mBluetoothAdapter;
公共同步void connect(蓝牙设备){
//启动ConnectThread以连接到给定设备
mConnectThread=新的连接线程(设备);
mConnectThread.start();
}
私有类ConnectThread扩展线程{
专用最终蓝牙插座mBluetoothSocket;
专用最终蓝牙设备mBluetoothDevice;
公共连接线程(蓝牙设备){
//使用稍后指定给mmSocket的临时对象,
//因为mmSocket是最终的
mBluetoothDevice=设备;
BluetoothSocket tmp=null;
//获取BluetoothSocket以连接给定的BluetoothDevice
试一试{
//MY_UUID是应用程序的UUID字符串
tmp=device.createInsurerCommsocketToServiceRecord(我的UUID);
}捕获(IOE异常){
}
mBluetoothSocket=tmp;
}
公开募捐{
//因为BuluetoothAdapter.discovery()是
//重磅程序,取消任何打开
//在尝试连接之前进行查找
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.cancelDiscovery();
//通过套接字连接设备。这是阻止调用,因此
//将在成功连接或异常时返回
//连接到BluetoothSocket
试一试{
//通过套接字连接设备。这是阻止调用,因此
//将在成功连接或异常时返回
mBluetoothSocket.connect();
}捕获(IOE异常){
试一试{
//无法连接,请关闭套接字并重试