android蓝牙发送图片demo
时间: 2023-07-22 11:31:23 浏览: 113
以下是一个简单的Android蓝牙发送图片的Demo,仅供参考:
1. 首先在AndroidManifest.xml文件中添加蓝牙权限:
```xml
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
```
2. 在需要发送图片的Activity中,创建蓝牙Socket连接:
```java
private BluetoothAdapter bluetoothAdapter;
private BluetoothDevice bluetoothDevice;
private BluetoothSocket bluetoothSocket;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private void connectToDevice() {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothDevice = bluetoothAdapter.getRemoteDevice("MAC_ADDRESS_OF_REMOTE_DEVICE");
try {
bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(MY_UUID);
bluetoothSocket.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
```
其中,MAC_ADDRESS_OF_REMOTE_DEVICE需要替换为远程设备的MAC地址。
3. 发送图片数据:
```java
private void sendImage() {
OutputStream outputStream;
try {
outputStream = bluetoothSocket.getOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
outputStream.write(byteArray);
} catch (IOException e) {
e.printStackTrace();
}
}
```
其中,R.drawable.image需要替换为实际的图片资源ID。
4. 完整代码:
```java
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter bluetoothAdapter;
private BluetoothDevice bluetoothDevice;
private BluetoothSocket bluetoothSocket;
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);
connectToDevice();
sendImage();
}
private void connectToDevice() {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothDevice = bluetoothAdapter.getRemoteDevice("MAC_ADDRESS_OF_REMOTE_DEVICE");
try {
bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(MY_UUID);
bluetoothSocket.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendImage() {
OutputStream outputStream;
try {
outputStream = bluetoothSocket.getOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
outputStream.write(byteArray);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
需要注意的是,由于蓝牙传输的数据量比较大,需要使用异步线程进行发送,避免阻塞主线程。此外,需要确保远程设备已经开启蓝牙,并且已经配对。
阅读全文