在Android设备之间通过蓝牙接收文本数据?

时间:2012-11-30 09:54:32

标签: android bluetooth

我正在开发一款Android应用,我需要使用蓝牙接口将文本从一台设备传输到另一台设备。 问题是,我的广播接收器不工作,因为它应该工作。当从一个设备发送数据时,我的接收器设备的广播监听器根本不起作用。 我目前正在使用以下代码:

以下代码用于连接蓝牙设备:

protected void connect(BluetoothDevice device) {
try {
ConfigClass.isFirstBluetoothSignal=true;
Log.d(TAG,"connect bluetooth");
// Create a Socket connection: need the server's UUID number of
// registered
Method m = device.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
socket = (BluetoothSocket) m.invoke(device, 1);
// socket=device.createRfcommSocketToServiceRecord(MY_UUID_INSECURE);
socket.connect();
Log.d(TAG, ">>Client connectted");
inputStream = socket.getInputStream();
socket.getOutputStream();
int read = -1;
final byte[] bytes = new byte[1024];
while (true) {
synchronized (obj1) {
read = inputStream.read(bytes);
//_handler.obtainMessage(RECIEVE_MESSAGE, -1, read).sendToTarget();
Log.d(TAG, "read:" + read);
if (read > 0) {
ConfigClass.isFirstBluetoothSignal=false;
final int count = read;
String str = SamplesUtils.byteToHex(bytes, count);
// Log.d(TAG, "test1:" + str);
hex = hexString.toString();
if (hex == "") {
hexString.append("<--");
} else {
if (hex.lastIndexOf("<--") < hex.lastIndexOf("-->")) {
hexString.append("\n<--");
}
}
hexString.append(str);
hex = hexString.toString();
// Log.d(TAG, "test2:" + hex);
if (hex.length() > maxlength) {
try {
hex = hex.substring(hex.length() - maxlength,
hex.length());
hex = hex.substring(hex.indexOf(" "));
hex = "<--" + hex;
hexString = new StringBuffer();
hexString.append(hex);
}catch (NullPointerException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "e", e);
}
}
_handler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), hex, Toast.LENGTH_LONG);
}
});
}
}
}
} catch (Exception e) {
ConfigClass.isFirstBluetoothSignal=false;
Log.e(TAG, ">>", e);
Toast.makeText(getBaseContext(),
getResources().getString(R.string.ioexception),
Toast.LENGTH_SHORT).show();
return;
} finally {
if (socket != null) {
try {
Log.d(TAG, ">>Client Socket Close");
socket.close();
socket = null;
// this.finish();
return;
} catch (IOException e) {
Log.e(TAG, ">>", e);
}
}
}
}

以下代码是接受传入连接:

public class AcceptThread extends Thread{
// The local server socket
private final BluetoothServerSocket mmServerSocket;
private String mSocketType;
private BluetoothAdapter mAdapter=BluetoothAdapter.getDefaultAdapter();

public AcceptThread(boolean secure) {
BluetoothServerSocket tmp = null;
mSocketType = secure ? "Secure":"Insecure";

// Create a new listening server socket
try {
if (secure) {
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID_SECURE);
} else {
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e);
}
mmServerSocket = tmp;
}

public void run() {

//BluetoothSocket socket = null;

// Listen to the server socket if we're not connected
while (true) {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket.accept();
//InputStream ins=socket.getInputStream();

/*BufferedReader r = new BufferedReader(new InputStreamReader(ins));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}*/

//System.out.println("Data============================================>>>"+line);
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "accept() failed", e);
break;
}

// If a connection was accepted
if (socket != null) {
synchronized (SearchDeviceActivity.this) {

ConnectedThread connectedThread=new ConnectedThread(socket, device.getAddress());
connectedThread.start();
//socket.close();
break;
}
}
}

}
}

以下代码用于获取传入数据:

private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;

@SuppressLint({ "NewApi", "NewApi" })
public ConnectedThread(BluetoothSocket socket, String socketType) {
Log.d(TAG, "create ConnectedThread: " + socketType);
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;

// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}

mmInStream = tmpIn;
mmOutStream = tmpOut;
}

public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;

// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);

// Send the obtained bytes to the UI Activity
_handler.obtainMessage(SearchDeviceActivity.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
//connectionLost();
break;
}
}
}

/**
* Write to the connected OutStream.
* @param buffer The bytes to write
*/
@SuppressLint("NewApi")
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);

// Share the sent message back to the UI Activity
_handler.obtainMessage(SearchDeviceActivity.MESSAGE_WRITE, -1, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}

public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}

0 个答案:

没有答案