本文介绍了Android的样品蓝牙code通过蓝牙发送一个简单的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要发送一个简单的字符串数据,如A从Android设备到另一个通过蓝牙。我看了样品蓝牙code在Android SDK中,但它是对我来说太复杂。我不明白我怎么可以只发送特定的数据时,我preSS的按钮。我该如何解决这个问题呢?
解决方案
私人的OutputStream的OutputStream;
私人的InputStream inStream中;
私人无效的init()抛出IOException异常{
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
如果(blueAdapter!= NULL){
如果(blueAdapter.isEnabled()){
设置< BluetoothDevice类> bondedDevices = blueAdapter.getBondedDevices();
如果(bondedDevices.size()大于0){
BluetoothDevice类[]设备=(BluetoothDevice类[])bondedDevices.toArray();
BluetoothDevice类设备的设备= [0];
ParcelUuid []的UUID = device.getUuids();
的BluetoothSocket插座= device.createRfcommSocketToServiceRecord(UUID的[0] .getUuid());
Socket.connect()的;
的OutputStream = socket.getOutputStream();
inStream中= socket.getInputStream();
}
Log.e(错误,没有合适的配对设备。);
}其他{
Log.e(错误,蓝牙被禁用。);
}
}
}
公共无效写入(String s)将抛出IOException异常{
outputStream.write(s.getBytes());
}
公共无效的run(){
最终诠释BUFFER_SIZE = 1024;
byte []的缓冲区=新的字节[BUFFER_SIZE];
INT字节= 0;
INT B = BUFFER_SIZE;
而(真){
尝试 {
字节= inStream.read(缓冲区,字节,BUFFER_SIZE - 字节);
}赶上(IOException异常E){
e.printStackTrace();
}
}
}
I want to send a simple string data such as 'a' from an android device to other one via bluetooth. I looked sample bluetooth code in android sdk but it is so complex for me. I cannot understand how I can send only specific data when I press a button. How can I solve this problem?
解决方案
private OutputStream outputStream;
private InputStream inStream;
private void init() throws IOException {
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if(bondedDevices.size() > 0){
BluetoothDevice[] devices = (BluetoothDevice[]) bondedDevices.toArray();
BluetoothDevice device = devices[0];
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
}
Log.e("error", "No appropriate paired devices.");
}else{
Log.e("error", "Bluetooth is disabled.");
}
}
}
public void write(String s) throws IOException {
outputStream.write(s.getBytes());
}
public void run() {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int bytes = 0;
int b = BUFFER_SIZE;
while (true) {
try {
bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
这篇关于Android的样品蓝牙code通过蓝牙发送一个简单的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!