简体   繁体   English

Android-以编程方式通过蓝牙发送图像

[英]Android - send image through bluetooth programmatically

I have modified the Android Bluetooth Chat sample application to now send images across. 我已经修改了Android蓝牙聊天示例应用程序,现在可以发送图像了。 This is fine for the first image. 这对于第一个图像来说很好。 It gets sent across and displays correctly. 它被发送并正确显示。 When I try to send another image, it seems to send the previous image across 20+ times, when it should just send the new image over once. 当我尝试发送另一张图像时,它似乎发送了前20张以上的图像,而此时它应该只发送一次新图像。 I have tried using oef's but to no avail. 我曾尝试使用oef,但无济于事。

This sends the picture: 这发送图片:

        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);

This is in the ConnectedThread: 这是在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;
            }
        }
    }

This reads the data back in: 这将读回数据:

    case MESSAGE_READ:
    byte[] readBuf = (byte[]) msg.obj;
    Bitmap bmp = BitmapFactory.decodeByteArray(readBuf, 0, msg.arg1);

For transferring files you can make an explicit call to ACTION_SEND using intents. 要传输文件,您可以使用意图对ACTION_SEND进行显式调用。

With ACTION_SEND , a menu will popup with the application that can handle the file type you want to send, from which the user will need to select Bluetooth, and then the device of which to send the file. 使用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);

Additional Help: 其他帮助:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM