我修改了 Android 蓝牙聊天示例应用程序,现在可以发送图像。这对于第一张图片来说很好。它被发送并正确显示。当我尝试发送另一张图像时,它似乎将前一张图像发送了 20 多次,而它应该只发送一次新图像。我尝试过使用 oef,但无济于事。
这发送图片:
Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.rc_a);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
byte[] image = bytes.toByteArray();
mConnection.write(image);
这是在 ConnectedThread 中:
public void run() {
byte[] buffer = new byte[1024];
byte[] imgBuffer = new byte[1024 * 1024];
int pos = 0;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
int bytes = mmInStream.read(buffer);
System.arraycopy(buffer,0,imgBuffer,pos,bytes);
pos += bytes;
mHandler.obtainMessage(BtoothSetupActivity.MESSAGE_READ,
pos, -1, imgBuffer).sendToTarget();
} catch (IOException e) {
connectionLost();
break;
}
}
}
这会读回数据:
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
Bitmap bmp = BitmapFactory.decodeByteArray(readBuf, 0, msg.arg1);
最佳答案
要传输文件,您可以使用 Intent 显式调用 ACTION_SEND
。
使用ACTION_SEND
,将弹出一个菜单,其中包含可以处理您要发送的文件类型的应用程序,用户需要从中选择蓝牙,然后选择要发送的设备文件。
File sourceFile = new File("//mnt/sdcard/file.apk");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
Intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(sourceFile));
startActivity(intent);
其他帮助:
关于java - Android - 以编程方式通过蓝牙发送图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15440398/