我正在开发一个Android应用,该应用通过蓝牙将文件和一些数据发送到其他设备,然后获取一些数据。
首先,我尝试使用蓝牙插座来做到这一点。
class BluetoothService{
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
BluetoothAdapter adapter;
Handler handler;
Context context;
ConnectedThread mConnectedThread;
BluetoothService(Context context, Handler handler)
{
adapter = BluetoothAdapter.getDefaultAdapter();
this.context = context;
this.handler = handler;
}
void connect(BluetoothDevice device)
{
BluetoothSocket tmp = null;
try
{
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
}
catch (IOException e)
{
}
mConnectedThread = new ConnectedThread(tmp);
mConnectedThread.start();
//mConnectedThread.run();
}
class ConnectedThread extends Thread
{
private BluetoothSocket socket;
private InputStream inputStream;
private OutputStream outputStream;
ConnectedThread(BluetoothSocket tmpSocket)
{
InputStream tmpIn = null;
OutputStream tmpOut = null;
try
{
tmpIn = tmpSocket.getInputStream();
tmpOut = tmpSocket.getOutputStream();
} catch (IOException e)
{
}
socket = tmpSocket;
inputStream = tmpIn;
outputStream = tmpOut;
try
{
socket.connect();
}catch (IOException e)
{
}
}
public void run()
{
byte[] buffer = new byte[1024];
int bytes;
//while (true)//crash app
try
{
int bytesAvaiable = inputStream.available();
bytes = inputStream.read(buffer);
handler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
}catch (IOException e)
{
}
}
void write(byte[] bytes)
{
try
{
outputStream.write(bytes);
}catch (IOException e)
{
}
}
但是我失败了!套接字读写无法与蓝牙套接字连接。 然后尝试使用默认的蓝牙将文件发送到连接的设备。
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setPackage("com.android.bluetooth");
intent.setType("audio/*");
//intent.setDevice(address_paired_device);
startActivity(intent);
如何使用此代码将文件发送到连接的蓝牙设备?