基于蓝牙socket开发Android蓝牙通信

[url]http://www.cyqdata.com/android/article-detail-53225#[/url]

如何实现Android蓝牙通信?一般通过使用蓝牙虚拟串口,可以通过配置非常简单地实现,很多外置蓝牙GPS都用这种做法。
然而Android却不支持,因此不得不得使用第二种方式:蓝牙socket。
本示例不使用C++开发,借助于第三方.NET组件inthehand来实现。
手机端的初始化代码。其中的具体含义可参照http://android.tgbus.com/Android/tutorial/201103/346657.shtml。
private PrintStream mPrintStream = null;
private BufferedReader mBufferedReader = null;

BluetoothAdapter myBluetoothAdapter = null;
BluetoothServerSocket mBThServer = null;
BluetoothSocket mBTHSocket = null;


myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

myBluetoothAdapter.enable();//open bth

Intent discoverableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//使得蓝牙处于可发现模式,持续时间150s
discoverableIntent.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 150);
 下面是PC上的初始化核心代码:PC是作为客户端出现的。它需要通过搜索获取手机的蓝牙MAC地址,实现通信。GUID又名UUID,是标记硬件地址的一种方法。
/// <summary>
/// 打开端口
/// </summary>
/// <param name="Name">端口名称</param>
/// <returns>成功否</returns>
public bool OpenPort(string Name)
{
InTheHand.Net.Bluetooth.BluetoothRadio.PrimaryRadio.Mode = InTheHand.Net.Bluetooth.RadioMode.Connectable;
InTheHand.Net.Sockets.BluetoothClient cli = new InTheHand.Net.Sockets.BluetoothClient();
InTheHand.Net.Sockets.BluetoothDeviceInfo[] devices = cli.DiscoverDevices();
foreach (InTheHand.Net.Sockets.BluetoothDeviceInfo device in devices)//设备搜寻
{
device.Update();
device.Refresh();
MessageBox.Show("设备已找到");
break;
}


BluetoothDeviceInfo bd = new BluetoothDeviceInfo(devices[0].DeviceAddress);
bluetoothClient = new BluetoothClient();

Guid mGUID = Guid.Parse("fa87c0d0-afac-11de-8a39-0800200c9a66");
bluetoothClient.Connect(devices[0].DeviceAddress, mGUID);//客户端对地址实现连接,这是一个阻塞线程,需要服务器端的回应
ReceiveThread = new Thread(ReceiveMethod);
ReceiveThread.Start();

return true;
}
下面是手机接受PC端连接请求的方法:
1 if (connected)
2 {
3 return;
4 }
5 try
6 {
7 mBThServer = myBluetoothAdapter
8 .listenUsingRfcommWithServiceRecord(NAME_SECURE,
9 MY_UUID_SECURE);
10 } catch (IOException e)
11 {
12 // TODO Auto-generated catch block
13 e.printStackTrace();
14 }
15
16 try
17 {
18 mBTHSocket = mBThServer.accept();
19 } catch (IOException e)
20 {
21 // TODO Auto-generated catch block
22 e.printStackTrace();
23 }
24 try
25 {
26 mBufferedReader = new BufferedReader(new InputStreamReader(
27 mBTHSocket.getInputStream()));
28 } catch (IOException e1)
29 {
30 // TODO Auto-generated catch block
31 e1.printStackTrace();
32 }// 取得输入、输出流
33 try
34 {
35 mPrintStream = new PrintStream(
36 mBTHSocket.getOutputStream(), true);
37 connected = true;
38 } catch (IOException e)
39 {
40 // TODO Auto-generated catch block
41 e.printStackTrace();
42 }
要通过手机发送数据,执行以下代码即可:
mPrintStream.write(buff);
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}// 发送给服务器
mPrintStream.flush();
PC端的接受代码:
while (isConnecting)
{

try
{
Stream peerStream = bluetoothClient.GetStream();
peerStream.Read(buffer, 0, PACKETLENGTH);
//dataprocess();
}


catch (Exception ex)
{
isConnecting = false;
MessageBox.Show(ex.ToString());

}
以下有几个需要注意事项:
1:inthehand.net.personal是PC端上一定要用得到的库,但注意这个库函数的版本,版本弄错了是很浪费时间的。
2:手机设备的蓝牙硬件权限要打开,否则就没法运行。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于 Android Studio 的蓝牙通信示例代码: 1. 在 AndroidManifest.xml 文件中添加以下权限: ```xml <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> ``` 2. 在 layout 文件夹中创建一个布局文件 activity_main.xml: ```xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android"> <Button android:id="@+id/button_search" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Search Devices"/> <ListView android:id="@+id/list_devices" android:layout_width="match_parent" android:layout_height="wrap_content"/> <Button android:id="@+id/button_send" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Send Data"/> <EditText android:id="@+id/edit_text" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> ``` 3. 创建一个 BluetoothAdapter 对象以进行蓝牙通信。在 MainActivity.java 文件中添加以下代码: ```java public class MainActivity extends AppCompatActivity { private BluetoothAdapter bluetoothAdapter; private ArrayAdapter<String> devicesArrayAdapter; private ListView listView; private EditText editText; private Button buttonSearch, buttonSend; private BluetoothDevice device; private BluetoothSocket socket; private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // Check if the device supports Bluetooth if (bluetoothAdapter == null) { Toast.makeText(getApplicationContext(), "Bluetooth not supported", Toast.LENGTH_LONG).show(); finish(); return; } // Check if Bluetooth is enabled if (!bluetoothAdapter.isEnabled()) { Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, 0); } // Initialize UI components listView = findViewById(R.id.list_devices); editText = findViewById(R.id.edit_text); buttonSearch = findViewById(R.id.button_search); buttonSend = findViewById(R.id.button_send); devicesArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1); listView.setAdapter(devicesArrayAdapter); buttonSearch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { searchDevices(); } }); buttonSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sendData(); } }); } // Search for Bluetooth devices private void searchDevices() { devicesArrayAdapter.clear(); Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { devicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } // Start discovery of new devices bluetoothAdapter.startDiscovery(); registerReceiver(discoveryReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); } // Send data to the connected device private void sendData() { String data = editText.getText().toString(); try { OutputStream outputStream = socket.getOutputStream(); outputStream.write(data.getBytes()); outputStream.flush(); Toast.makeText(getApplicationContext(), "Data sent", Toast.LENGTH_LONG).show(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Error sending data", Toast.LENGTH_LONG).show(); } } // Broadcast receiver for discovering new devices private final BroadcastReceiver discoveryReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); devicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } }; // Connect to the selected device private void connectToDevice(String deviceAddress) { device = bluetoothAdapter.getRemoteDevice(deviceAddress); try { socket = device.createRfcommSocketToServiceRecord(MY_UUID); socket.connect(); Toast.makeText(getApplicationContext(), "Connected to " + device.getName(), Toast.LENGTH_LONG).show(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Error connecting to device", Toast.LENGTH_LONG).show(); } } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(discoveryReceiver); try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 4. 您可以在 MainActivity.java 文件中添加其他方法,例如取消搜索、断开连接等。请注意,此示例代码仅用于演示目的,您需要根据自己的需求进行修改和完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值